Answer the question
In order to leave comments, you need to log in
Nginx rewrite for a static site - how to add a slash to the end?
There is this config:
server {
listen 80;
server_name _;
root /public_html;
index index.html;
# remove multiple slashes
if ($request_uri ~ "^[^?]*?//") {
rewrite "^" $scheme://$host$uri permanent;
}
# drop html extension
if (!-f "${request_filename}index.html") {
rewrite ^/(.*)/$ /$1 permanent;
}
if ($request_uri ~* "/index.html") {
rewrite (?i)^(.*)index\.html$ $1 permanent;
}
if ($request_uri ~* ".html") {
rewrite (?i)^(.*)/(.*)\.html $1/$2 permanent;
}
location / {
try_files $uri.html $uri $uri/ =404;
}
}
example.com/index.html => example.com
(returns /public_html/index.html) example.com/foo/index.html => example.com/foo/
(returns /public_html/foo/index.html) example.com/foo.html => example.com/foo
(returns /public_html/foo.html) example.com/foo.html => example.com/foo/
rewrite ^([^.]*[^/])$ $1/ permanent;
Answer the question
In order to leave comments, you need to log in
It worked with this config:
server {
listen 80;
server_name _;
root /home/user/www/example.com/public_html;
index index.html;
# example.com/foo// => example.com/foo/
if ($request_uri ~ "^[^?]*?//") {
rewrite "^" $scheme://$host$uri permanent;
}
# example.com/index.html => example.com/
rewrite (?i)^(.*)index\.html$ $1/ permanent;
# example.com/foo => example.com/foo/
rewrite ^([^.]*[^/])$ $1/ permanent;
# example.com/foo.html => example.com/foo/
rewrite (?i)^(.*)/(.*)\.html $1/$2/ permanent;
# prevent access from example.com/index/
location ~ /index/ {
return 404;
}
location / {
# remove slash from url end for access .html files
# example.com/foo/ => example.com/foo
rewrite ^/(.*)/$ /$1 last;
try_files $uri.html $uri $uri/index.html $uri/ =404;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question