使用Nginx要在同一個(gè)域名下配置多個(gè)項(xiàng)目有兩種方式:
- nginx按不同的目錄分發(fā)給不同的項(xiàng)目
- 啟用二級(jí)域名,不同的項(xiàng)目分配不同的二級(jí)域名
1.nginx按不同的目錄分發(fā)給不同的項(xiàng)目:
server {
listen 80;
server_name example.com;
location ^~ /project1 {
proxy_pass http://localhost: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://localhost: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://localhost: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;
}
}
這里配置了三個(gè)項(xiàng)目:
- http://example.com/project1路徑分發(fā)到http://localhost:8081
- http://example.com/project2路徑分發(fā)到http://localhost:8082
- 其他路徑分發(fā)到http://localhost:8080
2.啟用二級(jí)域名,不同的項(xiàng)目分配不同的二級(jí)域名
注意:很多同學(xué)說(shuō)無(wú)效,原因是一定要先對(duì)二級(jí)域名添加A記錄到主機(jī),同一個(gè)域名可以添加N個(gè)二級(jí)域名到同一個(gè)主機(jī)
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost: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;
}
}
project1
server {
listen 80;
server_name project1.example.com;
location / {
proxy_pass http://localhost: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://localhost: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;
}
}
注意:這三個(gè)項(xiàng)目屬于不同的域名,項(xiàng)目之間通過(guò)http訪問(wèn)會(huì)存在跨域問(wèn)題。
到此這篇關(guān)于Nginx同一個(gè)域名配置多個(gè)項(xiàng)目的實(shí)現(xiàn)方法的文章就介紹到這了,更多相關(guān)Nginx同域名配置多項(xiàng)目?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!