在Nginx中配置监听不同端口来访问不同的项目是一种常见的部署方式。以下是详细的配置方法:
在nginx.conf
或sites-available/default
文件中添加多个server
块:
# 第一个项目监听8080端口
server {
listen 8080;
server_name localhost;
root /var/www/project1;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# 第二个项目监听8081端口
server {
listen 8081;
server_name localhost;
root /var/www/project2;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
更推荐的方式是为每个项目创建单独的配置文件:
在/etc/nginx/sites-available/
目录下创建两个配置文件:
project1.conf
project2.conf
project1.conf
内容:
server {
listen 8080;
server_name localhost;
root /var/www/project1;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
project2.conf
内容:server {
listen 8081;
server_name localhost;
root /var/www/project2;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
sites-enabled
目录:sudo ln -s /etc/nginx/sites-available/project1.conf /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/project2.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
如果项目是运行在不同端口的应用服务器:
# 项目1 - Node.js应用运行在3000端口
server {
listen 8080;
server_name localhost;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# 项目2 - Python Flask应用运行在5000端口
server {
listen 8081;
server_name localhost;
location / {
proxy_pass http://localhost:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# HTTP重定向到HTTPS
server {
listen 8080;
server_name example.com;
return 301 https://$host$request_uri;
}
# HTTPS配置
server {
listen 8443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
root /var/www/project1;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
端口无法访问:
sudo ufw allow 8080/tcp
sudo netstat -tulnp | grep nginx
配置冲突:
server
块监听同一个端口权限问题:
sudo chown -R www-data:www-data /var/www/project1
配置测试:
sudo nginx -t
测试配置sudo systemctl restart nginx
或sudo systemctl reload nginx
应用更改通过以上配置,你可以轻松实现Nginx监听不同端口来服务不同的项目。