radar
radar

Reputation: 510

Nginx redirects static files to subdir of root

I have an app that runs at http://192.168.0.2:8080/. The index.html page is in /web folder and it requests static files (eg. css) at /css.

I'd like to use nginx as reverse proxy and to have myapp.mydomain.com to redirect to my app. I have the following configuration in my nginx.conf:

server {
        listen       80;
        server_name  myapp.mydomain.com;
        satisfy any;
        location / {
                proxy_pass  http://192.168.0.2:8080/web/;
                index  index.html index.htm;
        }
}

but it does not work for css files since it looks for them at /web/css. My workaround is to have my nginx.conf configured this way (without /web):

server {
            listen       80;
            server_name  myapp.mydomain.com;
            satisfy any;
            location / {
                    proxy_pass  http://192.168.0.2:8080/;
                    index  index.html index.htm;
            }
    }

and request http://myapp.mydomain.com/web each time.

But I'd like to be able to request http://myapp.mydomain.com/ and let nginx manage.

I think something similar to that may help but I can't find how:

location ~ .(css|img|js)/(.+)$ {
                try_files $uri /$uri /$1/$2;
        }

location / {
                proxy_pass  http://192.168.0.2:8080/web/;
                index  index.html index.htm;
        }

Here is my complete file, with auth etc:

upstream app { server 192.168.0.2:8080; }
server {
        listen       80;
        server_name  myapp.mydomain.com myapp.myOtherDomain.com;
        satisfy any;
        allow 192.168.0.0/24;
        deny all;
        auth_basic "closed site";
        auth_basic_user_file /etc/nginx/auth/passwords;
        location / { proxy_pass http://app/web/; }
        location /css { proxy_pass http://app; }
        location /img { proxy_pass http://app; }
        location /js { proxy_pass http://app; }
}

Any idea how I can fix that?

Thanks.

Upvotes: 1

Views: 2328

Answers (1)

Richard Smith
Richard Smith

Reputation: 49812

From what I understand, you have a working configuration and the only problem is that you would like the URL http://myapp.mydomain.com/ to be mapped to http://192.168.0.2:8080/web/.

Your working configuration is:

server {
  listen       80;
  server_name  myapp.mydomain.com;
  satisfy any;
  location / {
    proxy_pass  http://192.168.0.2:8080/;
    index  index.html index.htm;
  }
}

The simplest solution is to add an exact match for the / URI. Such as:

server {
  listen       80;
  server_name  myapp.mydomain.com;
  satisfy any;
  location = / { rewrite ^ /web/; }
  location / {
    proxy_pass  http://192.168.0.2:8080/;
    index  index.html index.htm;
  }
}

Upvotes: 2

Related Questions