Reputation: 12824
How can I redirect mydomain.example
and any subdomain *.mydomain.example
to www.adifferentdomain.example
using Nginx?
Upvotes: 226
Views: 313848
Reputation: 13
Just started using wordops and had a short domain name I use for email addresses that I needed to redirect to the primary long domain name for the website. My MX DNS entries for both domains pointed to an exchange server but the web service was on DigitalOcean. What I ended up doing was creating a basic wordops html site then editing the nginx conf to redirect specifically to the http address of the long domain name which THEN redirects to https. This solved my "warning" issue in firefox etc. This is what finally worked for me:
server {
listen 80;
listen 443;
server_name .shortname.com;
rewrite ^ http://stupidlongnamedomainname.com$request_uri? permanent;
}
Upvotes: 0
Reputation: 3651
Why use the rewrite module if you can do return
? Technically speaking, return
is part of the rewrite module as you can read here but this snippet is easier to read imho.
server {
server_name .domain.com;
return 302 $scheme://forwarded-domain.com;
}
You can also give it a 301 redirect.
Upvotes: 21
Reputation: 10684
Temporary redirect
rewrite ^ http://www.RedirectToThisDomain.example$request_uri? redirect;
Permanent redirect
rewrite ^ http://www.RedirectToThisDomain.example$request_uri? permanent;
In Nginx configuration file for specific site:
server {
server_name www.example.com;
rewrite ^ http://www.RedictToThisDomain.example$request_uri? redirect;
}
Upvotes: 4
Reputation: 3057
You can simply write a if condition inside server {} block:
server {
if ($host = mydomain.example) {
return 301 http://www.adifferentdomain.example;
}
}
Upvotes: 7
Reputation: 945
I'm using this code for my sites
server {
listen 80;
listen 443;
server_name .domain.example;
return 301 $scheme://newdomain.example$request_uri;
}
Upvotes: 26
Reputation: 375
If you would like to redirect requests for domain1.example
to domain2.example
, you could create a server block that looks like this:
server {
listen 80;
server_name domain1.example;
return 301 $scheme://domain2.example$request_uri;
}
Upvotes: 11
Reputation: 1516
That should work via HTTPRewriteModule.
Example rewrite from www.example.com
to example.com:
server {
server_name www.example.com;
rewrite ^ http://example.com$request_uri? permanent;
}
Upvotes: 13
Reputation: 820
server {
server_name .mydomain.example;
return 301 http://www.adifferentdomain.example$request_uri;
}
http://wiki.nginx.org/HttpRewriteModule#return
and
http://wiki.nginx.org/Pitfalls#Taxing_Rewrites
Upvotes: 35
Reputation: 18310
server_name supports suffix matches using .mydomain.example
syntax:
server {
server_name .mydomain.example;
rewrite ^ http://www.adifferentdomain.example$request_uri? permanent;
}
or on any version 0.9.1 or higher:
server {
server_name .mydomain.example;
return 301 http://www.adifferentdomain.example$request_uri;
}
Upvotes: 394