我想用 nginx 提供两个文件夹:一个包含生成的 html 文件的文件夹,以及一个包含静态 html 和 php 脚本的文件夹,以此文件夹结构为例:
├─/var/www
│ ├─generated
│ │ ├─index.html
│ │ └─foo.html
│ ├─static
│ │ ├─index.html
│ │ ├─test.html
│ │ ├─phpinfo
│ │ │ └─index.php
从用户的角度来看,它应该是一个站点,并且 nginx 应该尝试为生成文件夹中的文件提供服务,然后为静态文件夹中的文件提供服务(如果是 php 脚本,则应该执行它)。 哪个 URL 应该映射到哪些文件的示例:
http://localhost -> /var/www/generated/index.html
http://localhost/index.html -> /var/www/generated/index.html
http://localhost/foo.html -> /var/www/generated/foo.html
http://localhost/test.html -> /var/www/static/test.html
http://localhost/phpinfo -> /var/www/static/phpinfo/index.php
http://localhost/phpinfo/index.php -> /var/www/static/phpinfo/index.php
http://localhost/nonexistent -> 404 page
also notice that nothing points to the "shadowed" /var/www/static/index.html becuase generated folder takes priority
这是我迄今为止尝试过的:
server {
server_name localhost;
listen 80;
root /var/www
location ~ \.(php|html)$ {
try_files = /generated$uri /static$uri =404;
fastcgi_pass unix:/run/phpfpm/shared.sock;
fastcgi_index index.php;
}
}
它基本上可以工作,但是 /index.html 或 /index.php 没有被附加,因此这两个测试失败:
http://localhost -> 403 forbidden (log: directory index of "/var/www/" is forbidden)
http://localhost/phpinfo -> 404 not found (log: open() "/var/www/phpinfo" failed (2: No such file or directory))
但非常奇怪的是,如果我在 /var/www/index.html 创建一个空文件,并重复失败的测试,我会得到不同的结果:
http://localhost -> 200, /var/www/generated/index.html (this is what I want)
http://localhost/phpinfo -> 404 not found (log: "/var/www/phpinfo/index.html" is not found (2: No such file or directory))
notice that the error message is different for the same phpinfo request, what's going on?
答案1
找到了一个解决方案(针对NixOS):
root = "/var/www";
extraConfig = ''
index index.php index.html;
'';
locations = {
"/".extraConfig = ''
rewrite ^([^.]*[^/])$ $1/ permanent;
try_files /generated$uri /generated$uri/ /static$uri /static$uri/ =404;
'';
"~ \.(php|html)$".extraConfig = ''
try_files $uri /generated$uri /static$uri =404;
fastcgi_pass unix:${config.services.phpfpm.pools.shared.socket};
'';
}
这应该在 Nginx 配置中,但我还没有测试过:
http {
root /var/www;
index index.php index.html;
location / {
rewrite ^([^.]*[^/])$ $1/ permanent;
try_files /generated$uri /generated$uri/ /static$uri /static$uri/ =404;
}
location ~ \.(php|html)$ {
try_files $uri /generated$uri /static$uri =404;
fastcgi_pass unix:/run/phpfpm/shared.sock;
}
}