简体   繁体   中英

Nginx redirect *:port to subdomain

I'm working with Nginx and I want to know how can I redirect all request with a specific port to a subdomain ?

This is my default.conf :

server{
        listen 80 default_server;
        server_name localhost;

        location / {
                root /usr/share/nginx/html;
        }
}

server{
        listen 80;
        server_name blog.mydomain.com;

        location / {
                proxy_pass   http://my-ip:8080;
        }
}

So with this I have the default mydomain.com serve the html folder, and a subdomain blog.mydomain.com serve an application running port 8080.

My problem is when I try to access directly my-ip:8080 , or mydomain.com:8080 or blog.mydomain.com:8080 the server serve the application running port 8080 and I want to redirect all these requests to blog.mydomain.com without the :8080 .

How can I do that ? Automatically redirect to blog.mydomain.com if I specify :8080 in the url ?

When you use my-ip:8080 or mydomain.com:8080 , you call directly your application, not nginx. The issue I see here is not "my webapp doesn't redirect to nginx" but "I have a proxy but my webapp is directly accessible from the internet".

A clean way to fix it is to hide your application from the internet and let nginx be the only way to contact it. Configure your application to listen on localhost (it looks like it listens on * or 0.0.0.0 , meaning all interfaces). Then, tell nginx to proxy requests to http://localhost:8080; .


If you really want to keep your application listening on *:8080 , you can add a HTTP header in nginx (like X-Forwarded-For with proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; ) and detect it in your application. Without it, redirect to nginx. Note that anyone can add HTTP headers...

There is two solutions for your problem:

If you can change code of application then you can handle HTTP request in application. You should be able get information about port from headers.

If you cannot change code of application but you can change port on which application is listening, then you can do redirect in nginx. To do this, you need start listening on port 8080 in nginx and redirect it to 80, and on 80 port you change proxy_pass to new port of application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM