简体   繁体   中英

Nginx server not redirect after rewrite file extension

I want to remove php file extension. So I searched and tried this code.

It works well but when I tried un-existed page.

it just said "File not found". before I write 'try_files $uri ...;' It return /404.html.

I tried try_files $uri =404; in .php$ but all pages return to /404.html.

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /var/www/html;

    include /etc/nginx/default.d/*.conf;

    location / {
            try_files $uri $uri.html $uri/ @extensionless-php;
            index index.html index.php;
     }

    location ~ \.php$ {
            root            html;
            fastcgi_pass    127.0.0.1:9000;
            fastcgi_index   index.php;
            fastcgi_param   SCRIPT_FILENAME /var/www/html$fastcgi_script_name;
            include         fastcgi_params;
    }

    location @extensionless-php {
            rewrite ^(.*)$ $1.php last;
    }


    error_page 404 /404.html;
        location = /40x.html {
            root /var/www/html;
    }

    error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /var/www/html;
    }


}

How Can I fix this??

You are passing .php files to the PHP processor without checking for existence.

You should modify your location ~ \\.php$ block so that nginx handles non-existent files with a 404 response, rather than letting PHP complain.

Try something like:

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

I have removed the extra root directive as it was just confusing, so that the block now inherits the correct value from the outer block. I have removed fastcgi_index which is not used in this case. I have ordered fastcgi_param below the include to avoid silently overwriting your fastcgi_param statements.

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