简体   繁体   English

在 NGINX 从 URI 中删除.html 扩展,没有重定向

[英]In NGINX remove .html extension from URI without redirect

I'm trying to modify my NGINX config to strip the.html extension from URI's before they are passed to my PHP based CMS.我正在尝试修改我的 NGINX 配置,以在将 URI 中的 .html 扩展名传递给我的基于 PHP 的 CMS 之前将其剥离。

In other words when a visitor enters:换句话说,当访客进入时:

http://www.example.com/foo.html http://www.example.com/foo.html

I want the URI to be changed to/;我希望将 URI 更改为 /;

http://www.example.com/foo http://www.example.com/foo

Without doing an actual browser redirect.无需进行实际的浏览器重定向。 This is easy enough to accomplish in Apache, but I can't seem to crack the nut in NGINX.这在 Apache 中很容易实现,但我似乎无法破解 NGINX 中的螺母。 Here is what I have in my config file that doesn't seem to work.这是我的配置文件中似乎不起作用的内容。

    location ~ \.html {
            rewrite ^(/.*)\.html(\?.*)?$ $1$2 last;
    }

    location / {
        try_files $uri $uri/  /index.php;       
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass    127.0.0.1:9000;
        include         fastcgi_params;
        fastcgi_param   REQUEST_URI     $request_uri;
        fastcgi_param  SCRIPT_FILENAME  $request_filename;
    }

Using this code the REQUEST_URI that PHP picks up is still /foo.html.使用此代码,PHP 获取的 REQUEST_URI 仍然是 /foo.html。

Possible answer to my own question, or at least a workaround.我自己的问题的可能答案,或者至少是一种解决方法。

So apparently $request_uri is always going to contain the original URI, not the rewrite - that is contained in $uri.所以显然 $request_uri 总是会包含原始 URI,而不是重写 - 包含在 $uri 中。 So to workaround this I'm using a variable to store and pass the modifed URI to PHP.因此,为了解决这个问题,我使用一个变量来存储修改后的 URI 并将其传递给 PHP。 I'm not really thrilled with this solution though.不过,我对这个解决方案并不感到兴奋。

location ~ \.html {
            rewrite ^(/.*)\.html(\?.*)?$ $1$2 last;
    }

    location / {
        set $new_uri $uri
        try_files $uri $uri/  /index.php;       
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass    127.0.0.1:9000;
        include         fastcgi_params;
        fastcgi_param   REQUEST_URI     $new_uri;
        fastcgi_param  SCRIPT_FILENAME  $request_filename;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM