Skip to content

Instantly share code, notes, and snippets.

@tgmgroup
Last active January 20, 2019 12:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgmgroup/5c4b9be5c16b5f313ae99c259b6d9970 to your computer and use it in GitHub Desktop.
Save tgmgroup/5c4b9be5c16b5f313ae99c259b6d9970 to your computer and use it in GitHub Desktop.
NGINX HTTP to HTTPS and Non-WWW to WWW Redirect Configuration
# NGINX Server Block for:
# Redirect non-www base domain (domain.com) to www (www.domain.com)
# Redirect HTTP to HTTPS SSL (HTTP2)
# Supports multiple domains and subdomains
# Created by George Liu (www.georgeliu.me / Github:tgmgroup)
# STEP 1 - Base HTTPS Block
server {
#Listen only on HTTPS, use STEP 3 to redirect from HTTP
listen 443 ssl http2;
listen [::]:443 ssl http2;
# Put Includes Here
# Change .domain1.com and .domain2.com to your own domain
# The .domain1.com wildcard format (DOT domain) catches all domains and subdomains of domain1.com
server_name .domain1.com .domain2.com;
# Put Server Configs Here
# Put Other Configs Here
}
# STEP 2 -  Redirect base (non-www URL) to HTTPS www
server {
listen 80;
listen [::]:80;
listen 443 ssl http2;
listen [::]:443 ssl http2;
# Catch only www subdomains on HTTP and HTTPS
server_name domain1.com domain2.com;
# Permanent redirect to HTTPS and www
return 301 https://www.$host$request_uri;
# Use the following if redirecting www to non-www URLs
#        server_name www.domain1.com www.domain2.com;
#        return 301 https://$host$request_uri;
# If using both HTTPS and HTTP (only www redirect), edit STEP 1 to include
#        listen 80;
#        listen [::]:80;
# and remove STEP 3
# and change the return 301 line to use "$scheme://" instead of "https://"
}
# STEP 3 -  Redirect all non- base-non-www HTTP to HTTPS
server {
listen 80;
listen [::]:80;
# Catch all base and subdomains on HTTP, including redirects from STEP 2
server_name .domain1.com .domain2.com;
# If user prefers, use "www.domain1.com *.domain1.com" combination instead of
# ".domain1.com" wildcard to avoid NGINX warnings
return 301 https://$host$request_uri;
}
@tgmgroup
Copy link
Author

tgmgroup commented Jan 10, 2017

Read more here: GL.me
Resources: 1, 2, 3, 4, 5, 6, 7, 8

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