【问题标题】:Set nginx root to a public folder while keeping the parent directory name in the URL将 nginx root 设置为公用文件夹,同时将父目录名称保留在 URL 中
【发布时间】:2017-10-25 19:32:38
【问题描述】:

在我们的网络项目中,我们有一个名为public 的目录。我们将 nginx 配置中的 root 设置为这个 public 文件夹,这样只有 public 文件夹中的文件才能通过 URL 访问。

我们的配置有点像这样:

server {
    listen       80;
    server_name  example.com

    root   /srv/nginx/example.com/v1/public;
    index  index.html index.php;

    location / {
        try_files $uri $uri/ /index.php;
        add_header Access-Control-Allow-Origin *;
    }

    location ~ \.php$ {
        fastcgi_intercept_errors on;
        fastcgi_index  index.php;
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_pass   php-fpm;
    }
}

所以现在我们可以通过 URL example.com 访问srv/nginx/example.com/v1/public。太好了。

但是我们怎样才能将我们的 URL 设置为 example.com/v1 并以 /srv/nginx/example.com/v1/public 为根呢?此外,如果我们上传一个新版本,它应该可以通过带有example.com/v2 的 URL 获得,根目录在 /srv/nginx/example.com/v2/public,而无需更改配置文件。

我认为我可以实现此目的的一种方法是在每次上传新版本时制作多个服务器块。但就像我说的,我不希望每次上传新版本时都更改 nginx 配置,并有做错事的风险。

还有什么其他方法?我该如何使用这些?

【问题讨论】:

    标签: nginx url-rewriting


    【解决方案1】:

    使用regular expression location block 将URI 拆分为两个部分,并使用alias directive 构造目标文件的路径(由$request_filename variable 表示)。

    例如:

    server {
        listen       80;
        server_name  example.com
    
        root   /var/empty;
        index  index.html index.php;
        add_header Access-Control-Allow-Origin *;
    
        location ~ ^/(?<prefix>[^/]+)/(?<suffix>.*)$ {
            alias /srv/nginx/example.com/$prefix/public/$suffix;
    
            if (!-e $request_filename) { rewrite ^ /$prefix/index.php last; }
    
            location ~ \.php$ {
                if (!-f $request_filename) { return 404; }
    
                fastcgi_intercept_errors on;
                include        fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME  $request_filename;
                fastcgi_pass   php-fpm;
            }
        }
    }
    

    由于this issue,请避免将try_file 与alias 一起使用。关于if的使用见this caution。

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 2019-07-12
      • 2022-10-06
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多