How to do rewrite correctly in Nginx?

1

I'm having trouble configuring Nginx as a reverse proxy in an application. It is a Rails application, which runs on unicorn.

In this case, I have the link domain. Instead of creating a subdomain, I'd like link to be the root url and direct the requisitions to my application. Looking at OS in English I saw some possible solutions. I tried some, and following the one that came closer to working, my configuration file looks like this:

upstream meuprojeto {
    server unix:/var/www/apps/meuprojeto/shared/tmp/sockets/meuprojeto.sock;
}

server {
    listen 80;
        server_name meuprojeto.com.br max_fails=0;
        index index.html;
        root /var/www/apps/meu_projeto/current/public;
        error_page 500 502 503 504 /500.html;
        client_max_body_size 4G;
        keepalive_timeout 10;

        error_log /var/log/nginx/meu_projeto.log debug;

        location /meuprojeto {
            rewrite ^/meuprojeto/(.*)$ /$1;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://meuprojeto/;
        }   
}

With this setting, when I access link , the request is correctly directed to the home page of my application, but all links will no longer work, since the url's generated are like link , when they should be something like link . What do I do to make it work? Is the configuration in Nginx or should it be done in Rails?

    
asked by anonymous 24.02.2016 / 22:52

2 answers

0

In order for the links in your application to work, you need to set the relative_url_root setting in the application as explained in Deploy to a subdirectory of Rails Guides.

    
25.02.2016 / 23:01
0

Assuming Unicorn and Rails are properly configured, you may want to use try_files as follows:

server {
    listen 80;
    server_name localhost;

    root /var/www/apps/meu_projeto/current/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://meuprojeto;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

After editing, save the file and restart ngninx:

sudo service nginx restart
    
24.02.2016 / 23:11