How to remove both .php and .html extensions from url using NGINX? How to remove both .php and .html extensions from url using NGINX? nginx nginx

How to remove both .php and .html extensions from url using NGINX?


From what I've researched, if you append your /etc/nginx/conf.d/domain.tld.conf file to include:

location / {    try_files $uri $uri.html $uri/ @extensionless-php;    index index.html index.htm index.php;}location ~ \.php$ {    try_files $uri =404;}location @extensionless-php {    rewrite ^(.*)$ $1.php last;}

Then restart nginx and give it a go. Hopefully this will help you! More information can be found (where I found it) here @ tweaktalk.net


No need for extra blocks and named locations and everything. Also move the index line outside the location block

server {  index index.html index.php;  location / {    try_files $uri $uri/ $uri.html $uri.php$is_args$query_string;  }  location ~ \.php$ {    try_files $uri =404;    # add fastcgi_pass line here, depending if you use socket or port  }}

Keep in mind that if you have a folder and a file with the same name inside the same folder, like /folder/xyz/ and /folder/xyz.php you won't be able to run the php file if the folder xyz contains an index.php or index.html, just keep this in mind.


To further Mohammad's answer, you might also want to offer redirects from .html and .php to the extensionless versions.

This can be accomplished due to the fact that $request_uri contains "full original request URI (with arguments)", and is not affected by the internal rewrites that are not visible to the user.

server {  index index.html index.php;  location / {    if ($request_uri ~ ^/(.*)\.html$) {  return 302 /$1;  }    try_files $uri $uri/ $uri.html $uri.php?$args;  }  location ~ \.php$ {    if ($request_uri ~ ^/([^?]*)\.php($|\?)) {  return 302 /$1?$args;  }    try_files $uri =404;    # add fastcgi_pass line here, depending if you use socket or port  }}