Nginx多端口多域名配置概述
在单一服务器环境中部署多个网站时,通常需要开放多个端口以区分不同的站点入口。虽然整体流程并不复杂,但在实际调试过程中耗费了约2小时,特此记录关键步骤。
主域名配合多端口的访问方案
首先需要在DNS NameServer中设置A记录。
具体操作是将主域名 www.xxx.com 指向服务器的IP地址。
接着需要开放所需的网络端口,并相应地修改Nginx的配置文件。
假设我们有两个服务分别运行在80端口和8080端口上。
如果服务器启用了iptables防火墙,需要先放行相关端口。
iptables -A INPUT -ptcp --dport 80 -j ACCEPT
iptables -A INPUT -ptcp --dport 8080 -j ACCEPT
随后修改Nginx的主配置文件。
#path: /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.xxx.com;
access_log /data/www/log/33.33.33.33_nginx.log combined;
index index.html index.htm index.php;
include /usr/local/nginx/conf/rewrite/none.conf;
root /data/www/website/33.33.33.33:80;
location ~ [^/]\.php(/|$) {
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
}
server {
listen 8080;
server_name A.xxx.com;
access_log /data/www/log/33.33.33.33:8080_nginx.log combined;
index index.html index.htm index.php;
include /usr/local/nginx/conf/rewrite/none.conf;
root /data/www/website/33.33.33.33:8080;
location ~ [^/]\.php(/|$) {
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
}
核心在于编写两个独立的server段配置。你也可以选择将这两段配置拆分为单独的文件,放置于特定目录下。
/etc/nginx/conf.d/
该目录通常用于存放额外的Nginx配置片段。
子域名配合多端口的访问方案
直接通过域名加端口的方式访问较为不便,因为用户必须输入类似 http://xxx.com:8080 的完整格式。
此外,若存在两种不同的后端服务,例如80端口对应PHP Web服务,而8080端口对应Node.js Web服务,且Node.js自身已在8080端口监听,此时该如何处理?
此时需要利用Nginx的反向代理功能,并在DNS Server中增加一条新的A记录,从而实现以下目标:
- www.xxx.com 直接访问80端口服务
- A.xxx.com 通过Nginx转发访问8080端口服务
首先在DNS中添加一条A记录。
将子域名 A.xxx.com 指向服务器IP。
Nginx的配置模板如下所示。
#path: /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.xxx.com;
access_log /data/www/log/33.33.33.33_nginx.log combined;
index index.html index.htm index.php;
include /usr/local/nginx/conf/rewrite/none.conf;
root /data/www/website/33.33.33.33:80;
location ~ [^/]\.php(/|$) {
fastcgi_pass unix:/dev/shm/php-cgi.sock;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico)$ {
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
expires 7d;
access_log off;
}
}
server {
listen 80;
listen [::]:80;
server_name A.XXX.com;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
fastcgi_send_timeout 300s;
fastcgi_read_timeout 300s;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
try_files $uri $uri/ =404;
}
}
配置完成后,重新载入Nginx配置文件使更改生效。
nginx -s reload
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。