Nginx多站点共用80端口配置方法
只需修改一处配置,即在Nginx的http模块中添加指向虚拟主机配置文件所在目录的包含语句:
具体示例如下:include /usr/local/nginx/default.d/*.conf;
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /usr/local/nginx/default.d/*.conf; //就这里加一行就可以了
}
第二步是创建用于存放虚拟主机配置的目录结构:
在/usr/local/nginx/路径下创建名为default.d的文件夹,专门用于存储各个网站的独立配置文件。
以下提供一个具体的配置文件示例:
/usr/local/nginx/default.d/mytest.conf
server {
listen 80 ; //注意这里,要把默认的那个default_server去掉,因为我们在下面要单独配置域名访问,所以这里不要留default_server,不然会报错。
server_name mytest.com; //这里写你想设置的域名,可以写多个,与名之间用空格隔开
root /mnt/share/mytest.com; //这里是你虚拟机的根目录,写绝对路径
# Load configuration files for the default server block.
location / {
index index.php index.html index.htm; //这里配置默认访问的页面
}
location ~* \.php$ { //这里配置php解析.php文件
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
}
error_page 404 /404.html; //默认的错误页面
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
另一个配置实例如下:
server {
listen 80;
server_name www.mytest1.com;
root /var/www/html;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico {
log_not_found off;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
若需添加更多虚拟机站点,操作方式相同:复制现有配置文件,并修改其中标注的关键参数即可!
完成虚拟机配置文件编写后,还需在Linux系统的hosts文件中添加对应的域名映射,否则访问时将跳转至外网。
vim /etc/hosts
127.0.0.1 mytest1.com
127.0.0.1 mytest.com
若需在Windows环境下访问Linux虚拟机中的网站,则必须在Windows系统中配置hosts文件,将所有相关域名指向Linux服务器的IP地址,例如:
192.168.0.27 mytest1.com
192.168.0.27 mytest.com
第六部分:常见问题排查:
nginx: [emerg] a duplicate default server for 0.0.0.0:80 in /etc/nginx/vhosts/
出现此类错误通常是因为:
server {
listen 80
在该处将80端口后的所有参数清除,仅保留端口号80,去除多余配置即可解决该问题。
总结
上述内容介绍了Nginx配置多个站点共用80端口的具体解决方法,希望能对大家有所帮助。如有任何疑问,欢迎留言,小编会及时回复。感谢大家对本站的支持!