tobi.g
tobi.g

Reputation: 946

Nginx SSL/Subdomain/IP redirect

at the moment I am running a website in nginx/1.6.3 on centOS7

Everything runs smooth, except some redirects.

This is what my .conf file looks like:

server {
  listen 443 ssl spdy default deferred;
  server_name .example.com;

  ... more configs

  }


server {
  listen 80;
  server_name .example.com;
  return 301 https://example.com$request_uri;
}

What I would like to accomplish are the following scenarios:

user visits in browser              | this should happen
------------------------------------|-------------------------------------
https://example.com$request_uri     | Just deliver content
https://*.example.com$request_uri   | 301 https://example.com$request_uri
https://123.123.123.123$request_uri | 301 https://example.com$request_uri
http://example.com$request_uri      | 301 https://example.com$request_uri
http://*.example.com$request_uri    | 301 https://example.com$request_uri
http://123.123.123.123$request_uri  | 301 https://example.com$request_uri

Upvotes: 6

Views: 466

Answers (2)

singer
singer

Reputation: 2636

I used this pattern to solve a similar problem:

server_name   ~^(?<subdomains>.+\.)?(?<domain>[^.]+\.[^.]+)$;
if ($domain != 'example.com') {
        rewrite ^/(.*)$  http://${subdomains}example.com/$1  permanent;
}

And so on

Upvotes: 0

skbly7
skbly7

Reputation: 1162

Please check running with following config, this should work.

#This would serve all your content.
server {
  listen 443 ssl spdy default deferred;
  server_name example.com;

  ... more configs

}

#https calls to anything except example.com would be redirected here    
server {
  listen 443 ssl spdy default deferred; #(Can also use only : "listen 443;")
  server_name *.example.com 123.123.123.123;
  return 301 https://example.com$request_uri;
}

#All port 80 redirection to https://example.com
server {
  listen 80;
  server_name example.com *.example.com 123.123.123.123;
  return 301 https://example.com$request_uri;
}

Upvotes: 1

Related Questions