Nicolas Berthier
Nicolas Berthier

Reputation: 508

nginx redirection to index page

I am struggling to implement an automatic nginx redirect from non index pages to my index page, with the exception of /admin

For instance, example.com/test should redirect to example.com, but example.com/admin should not redirect to example.com

This is my current nginx configuration file:

upstream app_server {
    server unix:/tmp/mysite.sock;
}

proxy_cache_path /var/www/example.com/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; 

server {
    listen 80;
    server_name www.example.com example.com;

    # redirects both www and non-www to https
    return 301 https://www.example.com$request_uri;
    
}

server {
    listen 443;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
    }

server {

    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;

    server_name  www.example.com;
    
    ssl_certificate     /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

    charset     utf-8;

    client_max_body_size 75M;

    location /media  {
        alias /var/www/example.com/media;
    }

    location /static {
        alias /var/www/example.com/static;
    }

    location / {
        proxy_cache my_cache;
        include proxy_params;
        proxy_pass http://app_server;
        proxy_ssl_server_name on;
    }
}

I have tried adding a try_files statetement within my location / block, and other things, but none seem to work. Am I missing something?

Upvotes: 0

Views: 156

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15470

You are trying to mix proxy_pass with try_files, it won't work within the same location block. You can use named location instead and rewrite any URI that doesn't start with /admin to a root one using negative regex assertion:

location / {
    try_files $uri @app;
}
location @app {
    rewrite ^(?!/admin) / break;
    proxy_cache my_cache;
    include proxy_params;
    proxy_pass http://app_server;
}

You don't need the separate location /media { ... } or location /static { ... } blocks, because as nginx documentation states:

When location matches the last part of the directive’s value:

location /images/ {
    alias /data/w3/images/;
}

it is better to use the root directive instead:

location /images/ {
    root /data/w3;
}

Instead you just need to define the common server root (outside of any location blocks):

root /var/www/example.com;

You are also don't need to use the proxy_ssl_server_name directive since you are not proxying your request to the upstream with HTTPS protocol.

Upvotes: 2

Related Questions