Last active
October 17, 2020 10:50
-
-
Save jaw-sh/2dd0eb3be4c0845813e4 to your computer and use it in GitHub Desktop.
NGINX catch-all for redirecting www and http to non-www https
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Redirect http:// to https:// | |
server { | |
listen 80 default_server; | |
listen [::]:80 default_server; | |
server_name _; | |
return 301 https://$host$request_uri; | |
} | |
# Redirect https://www to https:// | |
server { | |
# Setting default_server on these can cause redirect loops. | |
listen 443 ssl; | |
listen [::]:443 ssl; | |
ssl_certificate /etc/nginx/ssl/mysite.pem; | |
ssl_certificate_key /etc/nginx/ssl/mysite.key; | |
server_name ~^www.(?<domain>.+)$; | |
return 301 https://$domain$request_uri; | |
} | |
# Your website details | |
server { | |
# Only listen to 443. | |
# default_server works here. | |
listen 443 ssl; | |
listen [::]:443 ssl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Worth noting that if you use this with Cloudflare you must make Crypto -> SSL set to "Full", or Cloudflare will channel HTTPS requests to port 80 and confuse nginx into an infinite loop.