使用nginx配置二级域名

时间:2023-03-09 07:14:06
使用nginx配置二级域名

使用nginx配置二级域名

2018.11.21 11:51:17字数 613阅读 170

最近想把三个项目配在一个服务器上,于是想使用nginx配置二级域名实现。

1.域名添加解析

我的是阿里云的域名,所以首先给自己的域名添加解析。

打算使用www.codeliu.comtest1.codeliu.comtest2.codeliu.com这三个域名,其中 test1.codeliu.comtest2.codeliu.com作为二级域名。

使用nginx配置二级域名
解析www.codeliu.com
使用nginx配置二级域名
解析test1.codeliu.com
使用nginx配置二级域名
解析test2.codeliu.com

2.准备好三个项目

eclipse新建三个web项目,直接在index.html中写一点东西能进行区别进行,然后export成war包,传到服务器的tomcat webapp目录下。

3.配置nginx

为了方便,我就直接在nginx.conf进行配置了,没有重新起配置文件,如果想重新起配置文件,可以在nginx.conf使用include进行包含就行。

vim /usr/local/nginx/conf/nginx.conf

使用上面的命令编辑nginx的配置文件,先把配置文件中的server注释掉,然后添加下面的语句

server {
listen ;
server_name www.codeliu.com; location / {
root /usr/lib/apache-tomcat-8.5./webapps/CodeliuDemo;
index index.html index.htm;
}
} server {
listen ;
server_name test1.codeliu.com; location / {
root /usr/lib/apache-tomcat-8.5./webapps/Test1Demo;
index index.html index.htm;
}
} server {
listen ;
server_name test2.codeliu.com; location / {
root /usr/lib/apache-tomcat-8.5./webapps/Test2Demo;
index index.html index.htm;
}
}

重启nginx

/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload

这样配置就完成了,输入不同的网站就可以显示不同的项目。

4.遇到的问题

在配置完成之后,访问出现了403。

4.1 首先看看是否有index文件

检查后发现都有,应该不是这个原因。

4.2 再检查是否是文件夹的权限问题

chmod -R 777

使用上面的命令后还是不行。

4.3 检查启动用户和nginx工作用户是否一致

修改nginx.conf的第一行,改成下面这样

user  root;

重启nginx,访问正常。


2018-11-21 15:21再次更新

试了试发现访问动态项目是404,所以决定一个项目使用一个tomcat,分配不同的端口,这样一个tomcat挂了不会影响其他的项目。

所以解压了三个tomcat,分别对应8080,8081,8082端口。修改tomcat的server.conf达到修改端口的目的。要改三个地方

<!-- 这里我把8005改成8006 -->
<Server port="" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener" />
<!-- 这里我把8080改成8081 -->
<Connector port="" protocol="HTTP/1.1"
connectionTimeout=""
redirectPort="" />
<!-- 这里我把8009改成8010 -->
<Connector port="" protocol="AJP/1.3" redirectPort="" />

重启三个tomcat

修改nginx.conf(上面已经配置过,直接在此基础上修改)

server {
listen ;
server_name www.qidaochina.com; location / {
proxy_pass http://127.0.0.1:8081;
index index.html index.htm;
}
} server {
listen ;
server_name ccmp.qidaochina.com; location / {
proxy_pass http://127.0.0.1:8080;
index index.html index.htm;
}
} server {
listen ;
server_name xwgk.qidaochina.com; location / {
proxy_pass http://127.0.0.1:8082;
index index.html index.htm;
}
}

其实就是把root改成了proxy_pass。这样就能把请求转发到对应的tomcat去处理。

本来想直接把项目名改成ROOT(tomcat的默认显示项目),但发现报错500,于是放弃了这种想法,而是更改ROOT下面的index.jsp.

<%@ page session="false" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head> <body>
<script type="text/javascript">
window.location.href="../CodeliuDemo/index.html";
</script>
</body>
</html>

这样就ok了。