最近想把三个项目配在一个服务器上,于是想使用nginx配置二级域名实现。
我的是阿里云的域名,所以首先给自己的域名添加解析。
打算使用 www.codeliu.com , test1.codeliu.com, test2.codeliu.com这三个域名,其中 test1.codeliu.com, test2.codeliu.com作为二级域名。
eclipse新建三个web项目,直接在index.html中写一点东西能进行区别进行,然后export成war包,传到服务器的tomcat webapp目录下。
为了方便,我就直接在nginx.conf进行配置了,没有重新起配置文件,如果想重新起配置文件,可以在nginx.conf使用include进行包含就行。
vim /usr/local/nginx/conf/nginx.conf
使用上面的命令编辑nginx的配置文件,先把配置文件中的server注释掉,然后添加下面的语句
server {
listen 80;
server_name www.codeliu.com;
location / {
root /usr/lib/apache-tomcat-8.5.33/webapps/CodeliuDemo;
index index.html index.htm;
}
}
server {
listen 80;
server_name test1.codeliu.com;
location / {
root /usr/lib/apache-tomcat-8.5.33/webapps/Test1Demo;
index index.html index.htm;
}
}
server {
listen 80;
server_name test2.codeliu.com;
location / {
root /usr/lib/apache-tomcat-8.5.33/webapps/Test2Demo;
index index.html index.htm;
}
}
重启nginx
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
这样配置就完成了,输入不同的网站就可以显示不同的项目。
但你会发现,这样做是不行的,把三个项目放在同一个tomcat里,要挂三个一起挂了。
所以咱用三个tomcat,每个存放一个项目。
解压三个tomcat,分别对应8080,8081,8082端口。修改tomcat的server.conf达到修改端口的目的。要改三个地方
<!-- 这里我把8005改成8006 -->
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener" />
<!-- 这里我把8080改成8081 -->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- 这里我把8009改成8010 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
重启三个tomcat
修改nginx.conf(上面已经配置过,直接在此基础上修改)
server {
listen 80;
server_name www.codeliu.com;
location / {
proxy_pass http://127.0.0.1:8081;
index index.html index.htm;
}
}
server {
listen 80;
server_name test1.codeliu.com;
location / {
proxy_pass http://127.0.0.1:8080;
index index.html index.htm;
}
}
server {
listen 80;
server_name test2.codeliu.com;
location / {
proxy_pass http://127.0.0.1:8082;
index index.html index.htm;
}
}
其实就是把root改成了proxy_pass。这样就能把请求转发到对应的tomcat去处理。
在配置完成之后,访问出现了403。
4.1 首先看看是否有index文件
检查后发现都有,应该不是这个原因。
4.2 再检查是否是文件夹的权限问题
chmod -R 777
使用上面的命令后还是不行。
4.3 检查启动用户和nginx工作用户是否一致
修改nginx.conf的第一行,改成下面这样
user root;
重启nginx,访问正常。