Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

This question already has an answer here:

I want to redirect url's like: http://subdomain.domain.com/r/wtf to http://domain.com/r/wtf

How do I do this?

share|improve this question

marked as duplicate by kasperd, gtirloni, Jenny D, Ward, Magellan Sep 28 at 16:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers 3

up vote -4 down vote accepted

The simplest answer:

if ($host !~ ^domain\.tld$){
    rewrite ^/(.*) http://domain.tdl/$1 redirect;
}

Because you've asked all subdomains to one domain, so that rule would apply to any subdomain.

Edit: That meant to be inside a server definition, the one that is not the same as ^domain.tld$.

share|improve this answer
    
That worked perfectly well, thank you! :) –  Steve Mar 27 '13 at 18:10
    
Don't bother about using 'if' directive. I'm using in production for several years without ANY problems in servers with HUGE load. The concept that for each request you'll have a comparison and that behaviour is bad is erroneous. The first response I gave to you, as mentioned in last Edit was meant to be inside a server definition as cadmi proposed, but you have to do what fits your environment. So if you have only one server definition and still wants to redirect, USE IF. And, opposed to cadmi's suggestion to return 301, it's a BAD IDEA if you're not using CACHE-CONTROL headers. –  Marcel Mar 28 '13 at 20:25

If is evil!. And if on every request is double facepalm ...

server {
    listen 80;
    # listen 443;
    server_name *.domain.tld;
    return 301 $scheme://domain.tld$request_uri; 
}

server {
    listen 80;
    # listen 443;
    server_name domain.tld;

    # usual lines
}
share|improve this answer

With a rewrite rule, I have something like this in my nginx config doing exactly that:

if ($host !~ ^(www\.kaarsemaker\.net|ip\.seveas\.net)$) {
        rewrite ^(.*)$ http://www.kaarsemaker.net$1 permanent;
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.