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

My code doesn't work with second level tld's like domain.co.uk

Here is my conf:

  # add www.
  if ($host ~ ^(?!www)) {
   rewrite ^/(.*)$ http://www.$host/$1 permanent;
  }

  # remove subdomain
  if ($host ~ "^www\.(.*)\.(.*\.([a-z]{2,4}|[a-z]{2}\.[a-z]{2}))") {
   set $host_without_sub $2;
   rewrite ^/(.*)$ http://www.$host_without_sub/$1 permanent;
  }

EDIT: Now I'm using this. It works fine:

# rules
server {

    #general
    listen 80;

    # add www.
    if ($host ~ ^(?!www)) {
        rewrite ^/(.*)$ http://www.$host/$1 permanent;
    }

    # remove subdomain
    if ($host ~ "^www\.(.*?)\.(.{3,}\.([a-z]{2}\.[a-z]{2}|[a-z]{2,4}))$") {
        set $host_without_sub $2;
        rewrite ^/(.*)$ http://www.$host_without_sub/$1 permanent;
    }
share|improve this question

2 Answers 2

Your original configuration is not taking advantage of the nginx configuration. With a rewrite like that nginx will have to do extensive parsing on each request. If you are in an environment where performance and quick response time is essential then you'll want to use server blocks.

# Add www and redirect subdomains.
server {  
    listen      80;
    server_name domain.com *.domain.com;
    rewrite     ^ http://www.domain.com$request_uri permanent;
}

This way there is no complex parsing, Nginx uses a hash table for the server lookups and the rewrite uses the already parsed $request_uri variable.

share|improve this answer
    
I can not use server_name as I'm having thousands of domains with the same configuration. Or do you know a dynamic server_name filling? And I don't want to use sites-enabled/ as it is to complex to edit. Look at my question again. I've posted a working version. P.S. We did not found any performance differences with or without regex. –  mgutt May 27 '10 at 8:49

I'm not sure why you have two versions. Here's what I have in my config. it removes www. from the start of any domain:

server {
    # omitting listen/server_name/access_log/error_log

    if ($host ~* www\.(.*)) {
        set $wwwless $1;
        rewrite ^(.*)$ $scheme://$wwwless$1 permanent;
    }

    # locations, other rules, etc
}
share|improve this answer
    
"why you have two versions" Because you don't understand my question. They are completly different rewrites (add www, remove subdomains). –  mgutt May 27 '10 at 8:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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