Question on server_name_in_redirect

server {
listen 80;
server_name example.com:7788 example.com;
server_name_in_redirect on;
root /var/www/html/exampel/;
index index.php index.html;

According to the wiki, this should automatically redirect any request
to example.com to example.com:7788

If server_name_in_redirect is on, then Nginx will use the first value
of the server_name directive for redirects. If server_name_in_redirect
is off, then nginx will use the requested Host header.
http://wiki.nginx.org/NginxHttpCoreModule#server_name_in_redirect

But it didn’t work in my case. On nginx 0.8.44

So i had to use

if ($host ~* shop.2u4u.com.cn ) {
rewrite ^(.*)$ http://shop.2u4u.com.cn:7788$1 ; # $1 contains
‘/foo’, not ‘www.mydomain.com/foo
}

Which is not clean and fell in the category of nginx pitfall :frowning:
http://wiki.nginx.org/Pitfalls

Hello!

On Wed, Aug 25, 2010 at 05:08:31PM +0800, [email protected] wrote:

If server_name_in_redirect is on, then Nginx will use the first value
of the server_name directive for redirects. If server_name_in_redirect
is off, then nginx will use the requested Host header.
http://wiki.nginx.org/NginxHttpCoreModule#server_name_in_redirect

But it didn’t work in my case. On nginx 0.8.44

You misunderstood wiki. It says “nginx will use first value …
for redirects”, but it doesn’t say anything about “all request
will be redirected”. Server name will be only used if nginx
would issue redirect for some reason (e.g. directory redirect to
add trailing slash).

Note well: using port in server_name doesn’t make sense as nginx
only match hostname part of a request’s Host header against it.
Distinction between different ports is made at socket level.

If you want all requests to port 80 to be redirected to port 7788
you should write something like this:

server {
    listen 80;
    server_name example.com;
    rewrite ^ http://example.com:7788$request_uri?;
}

server {
    listen 7788;
    server_name example.com;
    ... here actual request processing ...
}

Maxim D.

Thank you for your explanation! Your solution is much elegant!

I have a follow up on this. Since the redirect is used for “issue
redirect for some reason (e.g. directory redirect to add trailing
slash).”, then, supposedly i can do this:

location ~ ^/download/.*$  {
# the rewrite works!
rewrite ^ http://example.com:7788$request_uri?;
}

It works! :slight_smile: Thank you! Now the site is running on deafutl port 80.
Users won’t notice the download is through port 7788 unless they look
at the header. Much better!

You misunderstood wiki. Â It says “nginx will use first value …
for redirects”, but it doesn’t say anything about “all request
will be redirected”. Â Server name will be only used if nginx
would issue redirect for some reason (e.g. directory redirect to
add trailing slash).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs