
Как удалить все расширения .html, а также все вхождения index.html из строки URL в Nginx?
http://www.mysite/index.html
к к http://www.mysite
http://www.mysite/articles/index.html
к к http://www.mysite/articles
http://www.mysite/contact.html
кhttp://www.mysite/contact
http://www.mysite/foo/bar/index.html
http://www.mysite/foo/bar
РЕДАКТИРОВАТЬ:Вот мой файл конфигурации:
сервер {
listen 80;
server_name staging.mysite.com;
root /var/www/staging.mysite.com;
index index.html index.htm;
access_log /var/log/nginx/staging.mysite.com.log spiegle;
#error_page 404 /404.html;
#error_page 500 503 /500.html;
rewrite ^(.*/)index\.html$ $1;
rewrite ^(/.+)\.html$ $1;
rewrite ^(.*/)index\.html$ $scheme://$host$1 permanent;
rewrite ^(/.+)\.html$ $scheme://$host$1 permanent;
location / {
rewrite ^/about-us /about permanent
rewrite ^/contact-us /contact permanent;
try_files $uri.html $uri/ /index.html;
}
}
решение1
Как переписать (передать очищенный URL в файловую систему/бэкэнд без изменения URL, отображаемого клиенту):
rewrite ^(.*/)index\.html$ $1;
rewrite ^(/.+)\.html$ $1;
АльтернативноВы можете сделать 301-редирект (клиент делает новый запрос):
rewrite ^(.*/)index\.html$ $scheme://$host$1 permanent;
rewrite ^(/.+)\.html$ $scheme://$host$1 permanent;
решение2
Принятый ответ, похоже, не сработал у меня. Я парень Apache, который переключается, так что это может не сработать на 100% во всех обстоятельствах, но это, похоже, сработало на моем сайте (статические html-страницы, просто тест):
index index.html;
error_page 404 404.html;
rewrite ^(/.+)\.html$ $1;
try_files $uri.html $uri/ =404;
Вот что делает это возможным:
- url => файл, к которому осуществляется доступ
- домен.com/ => index.html
- домен.com/somepage => somepage.html
- домен.com/arandompage => 404.html
Надеюсь, это поможет другим запутавшимся бывшим поклонникам Apache.