Nginx: перенаправить все с http на https, за исключением одного URL-шаблона
У меня есть сайт, который должен быть доступен только через HTTPS, кроме одного URL-шаблона (потому что у меня есть на некоторых страницах http-iframe, и я бы хотел избежать предупреждений о безопасности)
E.g. this pages should be redirected to https:
http://example.com
http://example.com/a/this-is-an-article
http://example.com/v/this-is-a-video
This pages should not be redirected to https (or should be redirected form https to http)
http://example.com/l/page-with-unsafe-iframe
http://example.com/l/other-page-with-unsafe-iframe
Ответы
Ответ 1
Если страницы iframe всегда находятся в одном каталоге, можно использовать простые расположения префикса.
server {
listen 443;
location /l/ { # redirect https iframe requests to http server
return 301 http://$server_name$request_uri;
}
# ...
}
server {
listen 80;
location / { # the default location redirects to https
return 301 https://$server_name$request_uri;
}
location /l/ {} # do not redirect requests for iframe location
# ...
}
Ответ 2
Вы можете использовать карту и простые правила переадресации, например:
map $uri $redirect_https {
/l/page-with-unsafe-iframe 0;
/l/other-page-with-unsafe-iframe 0; # you can use regex here
default 1;
}
server {
listen 443;
if ($redirect_https = 0) {
return 301 http://$server_name$request_uri;
}
# other code
}
server {
listen 80;
if ($redirect_https = 1) {
return 301 https://$server_name$request_uri;
}
# other code
}
Я должен упомянуть, что 301 перенаправление является хорошей практикой, в отличие от постоянной перезаписи.