简体   繁体   中英

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.

In other words when a visitor enters:

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

I want the URI to be changed to/;

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. 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.

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. So to workaround this I'm using a variable to store and pass the modifed URI to 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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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