Skip to content
Advertisement

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

I want my nginx make display all url’s clean.

With some research I’ve made the first case to work. It`s done by following configuration:

location / {
    root   html;
    index  index.html index.htm index.php;
    try_files $uri.html $uri/ =404; 
}

It works for indexhtml.html displaying as indexhtml, but nothing happens with .php. If I change $uri.html to $uri.php, it works neither for .html, neither .php. I`ve tried to put something similar in php location but without any success.

Any advices?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement