使用Nginx要在同一个域名下配置多个项目有两种方式:
1.nginx按不同的目录分发给不同的项目
2.启用二级域名,不同的项目分配不同的二级域名
1.nginx按不同的目录分发给不同的项目:
server {
listen 80;
server_name example.com;
location ^~ /project1 {
proxy_pass http://127.0.0.1:8081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ^~ /project2 {
proxy_pass http://127.0.0.1:8082;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
这里配置了三个项目:
http://example.com/project1路径分发到http://localhost:8081
http://example.com/project2路径分发到http://localhost:8082
其他路径分发到http://localhost:8080
2.启用二级域名,不同的项目分配不同的二级域名
project1
server {
listen 80;
server_name project1.example.com;
location / {
proxy_pass http://127.0.0.1:8081;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
project2
server {
listen 80;
server_name project2.example.com;
location / {
proxy_pass http://127.0.0.1:8082;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
注意:这三个项目属于不同的域名,项目之间通过http访问会存在跨域问题。