Nginx rewrite certain port to subpath (nginx + uwsgi + django)

djangonginxreverse-proxyrewriteuwsgi

My goal is to rewrite everything under http://localhost:8000 to http://localhost/foo

I followed every step mentioned in this link, but still couldn't get it work.

Here's my settings:

urls.py (Django)

urlpatterns = [
    url(r'^$', 'home.view'),
    url(r'^foo$', 'foo.view'),
]

uwsgi.ini (uWSGI)

[uwsgi]

chdir           = /home/user/folder/project
wsgi-file       = /home/user/folder/project/iTrends/wsgi.py
home            = /home/user/.pyenv/versions/project
master          = true
processes       = 10
threads         = 5
socket          = /tmp/project.sock
chmod-socket    = 666
vacuum          = true
logto           = /tmp/project_uwsgi.log
http-websocket  = true
buffer-size     = 65535

nginx80.conf (nginx with port 80)

server {
    listen       80;
    server_name = _;

    location /test {
        rewrite ^/test/(.*)$ /$1 break;   
        proxy_pass  http://127.0.0.1:8000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

nginx8000.conf (nginx with port 8000)

server {
    listen      8000;
    server_name _; 
    charset     utf-8;

    client_max_body_size 75M;

    location /static {
        alias /home/user/folder/project/static_all;
    }

    location / {
        uwsgi_pass  unix:///tmp/project.sock;
        include     /etc/nginx/uwsgi_params;
    }
}

Now
http://localhost/test is equivalent to http://localhost:8000

but when I go to http://localhost/test/foo, nginx tells me "not found"
(I expect this the same as http://localhost:8000/foo)

What did I miss?

Best Answer

It seems that the problem is the extra $ in the rewrite rule (in the first argument). I removed it and it has started working fine.

    location /test {
        rewrite ^/test/(.*) /$1 break;   
        proxy_pass  http://127.0.0.1:8000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }