【问题标题】:Setup nginx to serve static html web pages based on url设置 nginx 以根据 url 提供静态 html 网页
【发布时间】:2016-01-21 00:26:25
【问题描述】:

我喜欢根据用户输入的 url 为不同的网站提供服务。 例如,如果用户将去

my-domain.pl/ 内容将从桌面文件夹提供

my-domain.pl/desktop 内容将从 desktop 文件夹提供

my-domain.pl/mobile 内容将从 mobile 文件夹提供

 root
  |
  |---mobile
  |      |--- assets
  |              |---js,css,img
  |      
  |---desktop
         |--- assets
                 |---js,css,img

我在 nginx 设置文件中尝试过:

 server {

    root /desktop

    location /mobile {
        root /mobile
    }    

    location /desktop{
        root /desktop
    }    

 }

但它仅适用于/ 路径,其余路径返回404

我尝试添加try_files $uri index.html,但它似乎为该位置的所有请求返回 index.html 文件,例如它也返回 index.html 文件而不是 javascript。

我在设置 nginx 方面绝对是新手,因此我们将不胜感激。

【问题讨论】:

    标签: nginx


    【解决方案1】:

    您需要使用alias 指令而不是root:请参阅documentation

    server {
    
        root /;
    
        location /desktop {
        }    
    
        location /mobile {
            alias /mobile;
        }    
     }
    

    (不要忘记结尾的分号)

    【讨论】:

      【解决方案2】:

      您应该避免在 location 块内指定 root(参见 nginx pitfalls)。

      您是否尝试过以下方法:

      • 只有一个root
      • 默认使用rewrite服务/desktop

      配置如下:

      server {
      
        root /;
      
        ## this should take care of the redirect to /desktop by default:
        location = / {
          rewrite ^ /desktop/ redirect;
        }
        ## this one below probably doesn't work:
        # rewrite ^/$ /desktop/;
      
      }
      

      附:我现在无法使用 nginx 访问机器,因此无法检查 rewrite 语法。另见this answer

      【讨论】:

        猜你喜欢
        • 2020-03-26
        • 1970-01-01
        • 2012-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多