Skip to content

Instantly share code, notes, and snippets.

@fideloper
Last active February 15, 2017 22:09
Show Gist options
  • Save fideloper/d1bc2217fc8df332c2b5 to your computer and use it in GitHub Desktop.
Save fideloper/d1bc2217fc8df332c2b5 to your computer and use it in GitHub Desktop.
Nginx redirects
server {
# ...
# Redirect /book and any sub-uris
# e.g. /book/anything
# e.v. /book/whatever?maybe=a_query_too
location /book {
return 301 http://book.serversforhackers.com;
}
# Redirect an exact URI via `=` operator
location = /feed.xml {
# Redirect to /feed URI of current scheme and host
return 301 $scheme://$host/feed;
}
# Redirect based on regex
location ~ ^/(some_uri|or_another_uri)$ {
# Redirect to /the_correct_uri URI of current scheme and host
return 301 $scheme://$host/the_correct_uri;
}
# ...
}
# Example of redirect www to non-www
server {
# Enforce the use of HTTPS
listen 80;
server_name www.serversforhackers.com;
# OR, capture all subdomains
# server_name *.serversforhackers.com;
return 301 http://serversforhackers.com$request_uri;
}
server {
listen 80 default_server;
server_name serversforhackers.com
}
@fideloper
Copy link
Author

This makes use of the location block over conditional statements for redirects.

Note the use of three varieties of location blocks, which capture "sub-uri's", exact URI's and regex captures.

@JacobBennett
Copy link

would this work for www redirect as well or would that require a different server block?

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