首页 > 解决方案 > 多个网站的Nginx反向代理和root问题

问题描述

我有一个服务器的 IP 地址,我想把我的网站前端和后端管理员放在上面。site1 部分​​应该在“ http://IP/ ”,而 site2 应该在“ http://IP/admin ”。

我已经在服务器中安装了 Nginx,并且我的网站文件在里面:可以说是这样的:

site1: /var/www/html/site1/index.html
site2: /var/www/html/site2/index.html

我在 /etc/nginx/site-available/ 中创建了 2 个名为 "site1.conf" 和 "site2.conf" 的文件。

站点1.conf:

 server {
    listen 80;
    listen [::]:80;

 root /var/www/html/site1;                                       
 index index.html index.htm;                                

 server_name http://myIP;                         

 location / {                                               

     try_files $uri $uri/ =404;                         
 } 
}                                                         

站点2.conf:

server {
    listen 80;
    listen [::]:80;
 server_name http://myIP;       

 location /admin {                      
 autoindex on;                          
 alias /var/www/html/site2;             
 try_files $uri $uri/ /index.html last; 
 index index.html;                      
 }
}  

然后我将这两个文件链接到“/etc/nginx/site-enabled”

重新启动 Nginx 后,我的“ http://ip/ ”打开 site1“index.html”并且工作正常。

但是“ http://ip/admin/ ”给出了 404 错误,而不是打开 site2 “index.html”

标签: nginxubuntu-16.04

解决方案


http://IP/并且http://IP/admin都指向同一个服务器,带有server_name“IP”。

您的服务器至少包含两个location块。

例如:

server {
    listen 80;
    listen [::]:80;
    server_name 1.2.3.4;

    root /var/www/html/site1;                                       
    index index.html index.htm;                                

    location / {                                               
        try_files $uri $uri/ =404;                         
    }

    location /admin {                      
        alias /var/www/html/site2;             

        ...
    }
}  

服务器名称仅包含 IP 地址或 DNS 名称的文本。有关更多信息,请参阅此文档


您可以将配置分布在您选择的任意数量的文件中。include参阅指令

nginx配置是一个名为的文件,nginx.conf其中包含一个include声明,用于获取sites-available目录中的所有文件。这些文件的内容包含在http { ... }.

正如我已经说过的,就您而言,您的两个服务是一个server { ... }nginx。但是,您仍然可以在其中创建一个包含来自其他位置的文件的server块文件。sites-available只是不要使用sites-avalableor conf.d,就像nginx使用这些目录名称一样。

例如:

sites-available/mysites.conf

server {
    listen 80;
    listen [::]:80;
    server_name 1.2.3.4;

    include /path/to/my/location/confs/*.conf;
}

并在/path/to/my/location/confs/site1.conf

root /var/www/html/site1;                                       
index index.html index.htm;                                

location / {                                               
    try_files $uri $uri/ =404;                         
}

并在/path/to/my/location/confs/site2.conf

location /admin {                      
    alias /var/www/html/site2;             

    ...
}

我并不是说这是组织文件的好方法,但有了nginx,很多事情都是可能的。


推荐阅读