重写请求 URL 并传递给 fast-cgi

重写请求 URL 并传递给 fast-cgi

我有一个如下的服务器块:

server {
    listen 80;

    # ...

    location / {
        try_files $uri $uri/ /index.php?$query_string;

        # I've tried adding "$uri.php" like so, but it downloads the php file instead.
        # try_files $uri $uri/ $uri.php /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

如果收到这样的请求http://example.com/random/page,我需要 Nginx 将其重写为,http://example.com/random/page.php而不更改用户的 URL。它还需要将该请求传递给其他位置块。如果该 php 文件不存在,它应该返回 404。我该如何实现这一点?

答案1

众多可能性之一:

server {
    listen 80;
    ...
    location / {
        try_files $uri $uri/ @rewrite;
    }
    location @rewrite {
        rewrite ^ $uri.php last;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        include fastcgi_params;
    }
}

location ~ \.php$无论如何,您都应该测试块中的文件是否存在,如本应用笔记

相关内容