I'm trying to setup a Nginx configuration for nice URLs without .html
extension.
What I currently have works, but the /
URI redirects to /index
and I don't want that.
The URL rewrite rules should be as follows:
/index.html -> /
/test.html -> /test
/subpage/ -> /subpage
/subpage/test.html -> /subpage/test
/sub/sub/index.html -> /sub/sub
/sub/sub/ -> /sub/sub
/somepage/ -> /somepage
/somepage.html -> /somepage
Here is the configuration:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
set $root /app/www/public;
if (!-d /app/www/public) {
set $root /config/www;
}
root $root;
index index.html;
error_page 401 /401;
error_page 403 /403;
error_page 404 /404;
error_page 500 502 503 504 /500;
location / {
#redirect index.html to /
if ( $request_uri ~ "index.html" ) {
rewrite ^(.*)/ $1/ permanent;
}
#remove .html from request
rewrite ^/(.*)\.html$ /$1 permanent;
#remove the trailing /
rewrite ^/(.*)/$ /$1 permanent;
try_files $uri.html $uri/ $uri =404;
}
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
}
location ~* \.(css|js)$ {
expires 7d;
}
# deny access to .htaccess/.htpasswd files
location ~ /\.ht {
deny all;
}
}
NOTE: this Nginx is running in a docker container.
if ( $request_uri ~ "index.html" )
because anif
statement inside alocation
has non-obvious behavior: nginx.com/resources/wiki/start/topics/depth/ifisevilif
statement. I'm pretty new to Nginx, coming from IIS there are a lot of things that are upside down from my point of view.