Reputation: 653
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?
Upvotes: 64
Views: 89315
Reputation: 835
This has worked for me for more than 5 years going.
location / {
try_files $uri/ $uri.html $uri.php$is_args$query_string;
}
Upvotes: 5
Reputation: 181
Perhaps this may be of use for you... It' Simple and gets the job done:
location / {
rewrite ^/([^\.]+)$ /$1.html break;
}
Upvotes: 2
Reputation: 42799
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.
Upvotes: 64
Reputation: 27218
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
}
}
Upvotes: 14
Reputation: 1015
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
Upvotes: 70