Skip to content

Instantly share code, notes, and snippets.

@jaw-sh
Last active October 17, 2020 10:50
Show Gist options
  • Save jaw-sh/2dd0eb3be4c0845813e4 to your computer and use it in GitHub Desktop.
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
# 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;
}
@jaw-sh
Copy link
Author

jaw-sh commented May 15, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment