Nginx - 根和别名之间的区别?

Rep*_*pox 3 nginx alias documentroot

我的目标是让 Laravel 安装与生成为静态内容的 Nuxt 应用程序一起运行。

我希望 Laravel 可用,当位置以/api. 这按预期工作。

对于任何其他请求,我希望 Nginx 为我提供另一个文件夹中的静态内容。

我可以通过更改第 18 行 ( ) 处的文档根root /var/www/html/public/dist;并将以下try_files配置更改为下面的配置中的内容来实现此目的。

我尝试换成root其他alias的,这给了我一些奇怪的结果。我从 Nginx 收到 500 服务器响应,错误日志中包含以下输出:

2020/09/29 13:28:17 [error] 7#7: *3 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 172.21.0.1, server: _, request: "GET /my/fake/url HTTP/1.1", host: "localhost"
172.21.0.1 - - [29/Sep/2020:13:28:17 +0000] "GET /claims/creat HTTP/1.1" 500 580 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" "-"
Run Code Online (Sandbox Code Playgroud)

我有以下配置(在 Docker 容器内运行)。

server {
    listen 80 default_server;

    root /var/www/html/public;

    index index.html index.htm index.php;

    server_name _;

    charset utf-8;

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt  { log_not_found off; access_log off; }

    error_page 404 /index.php;

    location / {
        alias /var/www/html/public/dist;
        try_files $uri $uri/ /index.html;
        error_page 404 /400.html;
    }

    location ~ /api {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不完全确定有什么区别,这也让我怀疑我是否应该使用aliasorroot在我的情况下,并且我希望能得到一些帮助来理解这一点。

Mic*_*ton 5

您的错误消息中的问题在于您的try_files,而不是您的rootalias。您尝试加载不存在的 URL 路径,在正常配置中,nginx 只会提供 404 错误或尝试加载 Web 应用程序的前端控制器。但你try_files告诉它服务/index.html。因此它开始尝试加载/index.html并以相同的方式结束try_files,但该文件也不存在,因此它给出了错误rewrite or internal redirection cycle while internally redirecting to "/index.html",因为它已经尝试加载/index.html

你应该先修复try_files. 例子:

try_files $uri $uri/ =404;           # static site
try_files $uri $uri/ /index.php;     # PHP front controller
Run Code Online (Sandbox Code Playgroud)

现在,回答你的第二个问题。

root指定实际的文档根目录,即文件系统上提供静态文件的目录,对应于 URL path /。例如,如果您有root /var/www/html/public并请求 URL /css/myapp.css,那么这将映射到文件路径/var/www/html/public/css/myapp.css

alias允许您将根目录下的某些 URL 路径重新映射到其他目录,以便您可以从其他地方提供静态文件。例如,对于 a,location /static/您可以定义alias /var/www/html/files/. 在这种情况下,将替换 中的 URL 路径部分root,而不是转到 的子目录。因此,请求将尝试加载文件而不是.aliaslocation/static//var/www/html/files//static/myapp.css/var/www/html/files/myapp.css/var/www/html/public/css/myapp.css

alias与 一起使用没有意义location /。如果需要在此处定义不同的文件路径,请使用root(但请注意,这可能是反模式)。