Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect address.com/foo/bar to address.com:port/bar with nginx?

Tags:

port

nginx

proxy

I have running nginx on my server ansel.ms and a node.js app on ansel.ms:46156.

I want to setup nginx so it redirects everything from

ansel.ms/rhythm

to

ansel.ms:46156.


ansel.ms/rhythm/sub/path

should become

ansel.ms:46156/sub/path

This is my file in sites-available:

upstream rhythm {
    server ansel.ms:46156;
}

server {
    listen   80;
    server_name ansel.ms www.ansel.ms;
    access_log /srv/www/ansel.ms/logs/access.log;
    error_log /srv/www/ansel.ms/logs/error.log;

    location / {
        root   /srv/www/ansel.ms/public_html;
        index  index.html index.htm;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param  SCRIPT_FILENAME  /srv/www/ansel.ms/public_html$fastcgi_script_name;
    }

    location /rhythm{
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://rhythm;
        proxy_redirect off;
    }
}

I do not really understand deeply what this does (the proxy_set_header stuff), I only copied & pasted it from several sources.

It doesn't work.

Can you give me a hint what to change so it does what I described above? Thank you!

like image 509
Anselm Eickhoff Avatar asked Dec 15 '10 12:12

Anselm Eickhoff


1 Answers

I cannot spot the error in your configuration file; I'm an nginx-newbie as well.

But here is my full nginx.conf config file which redirects http://myhost/cabaret/foo/bar to http://myhost:8085/foo/bar:

user www-data;
worker_processes  1;
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include     /etc/nginx/mime.types;
    access_log  /var/log/nginx/access.log;
    sendfile        on;
    keepalive_timeout  65;
    tcp_nodelay        on;

    server {

        listen   *:80; ## listen for ipv4
        access_log  /var/log/nginx/localhost.access.log;
        location /cabaret {
               rewrite /cabaret(.*) $1 break;
               proxy_pass http://127.0.0.1:8085;
               proxy_redirect     off;
               proxy_set_header   Host             $host;
               proxy_set_header   X-Real-IP        $remote_addr;
               proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
    }
}

It is not perfect, because it will not work with http://myhost/cabaret, only if a slash follows carabet like in http://myhost/cabaret/ or http://myhost/cabaret/foo/bar.

like image 104
hcs42 Avatar answered Oct 18 '22 19:10

hcs42