如何在Nginx的重写规则中包含所有php文件?

问题描述 投票:3回答:1

我要做的是允许以下任何一项工作:

site.mydomain.com/{id}?args(默认为index.php)

site.mydomain.com/{id}/{any file如果存在}?args(可能是calendar.php,upload.php等等。如果不是404会)

我在Nginx配置中的内容如下:

server {
    listen 80;

    large_client_header_buffers 4 32k;

    server_name site.mydomain.com;

    root /var/www/php/my_site/public;

    index index.php;

    access_log /var/log/sites/my_site.access.log;
    error_log /var/log/sites/my_site.error.log error;

    location / {
        rewrite ^/([0-9]+)/?$ /index.php?s=$1$is_args$args last;
        include /etc/nginx/conf.d/php.inc;
    }

    location ~ /\.ht {
        deny all;
    }
}

这是我的php.inc,我包括在我的位置,所以它实际上将执行PHP而不是下载它:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;

    fastcgi_param   SCRIPT_FILENAME    $request_filename;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;

    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

当我去site.mydomain.com/{id}它工作

如果我在它的末尾附加/index.php,我得到404错误,或任何其他PHP文件。

由于旧应用程序的向后兼容性,我需要index.php(和其他文件)。

我已经尝试了围绕SO和谷歌搜索的几个配置选项,但我似乎无法让它工作。我对nginx很新,所以我有点亏。

这是我的目录结构,如果它有帮助:

/var/www/php/my_site
    /application
    /library
    /public
        /static
            /styles
            /javascript

编辑

我尝试使用以下建议的答案:

rewrite ^/([0-9]+)(/|/index.php)?$ /index.php?s=$1 break;

它也做同样的事情。我已将我的问题更新为比以前更具体的问题。

php nginx ubuntu-18.04
1个回答
4
投票

可能的方法:

location / {
}

location ~ /\.ht {
    deny all;
}

location ~ ^/([0-9]+)($|/) {
    rewrite ^/([0-9]+)/?$ /index.php?s=$1 last;
    rewrite ^/([0-9]+)/(.*)\.php$ /$2.php?s=$1 last;
    rewrite ^/([0-9]+)/(.*)$ /$2 last;
}

location ~ \.php$ {
    try_files $uri =404;
    ...
}

最后三个location区块的顺序很重要。

include /etc/nginx/conf.d/php.inc;已移出location /区块并插入末端,因此它提供了顶级location ~ \.php$区块而不是嵌套位置区块。我在上面的示例中显示了include文件的内容,但是你的include语句将完全相同。

location ~ ^/([0-9]+)($|/)块处理以/{id}部分开头的任何URI。 rewrite自动将原始查询字符串附加到重写的URI。有关详细信息,请参阅this document

您应该在try_files块中包含location ~ \.php$语句,以避免发送uncontrolled requests to PHP并在PHP文件不存在时返回404响应。

© www.soinside.com 2019 - 2024. All rights reserved.