nael
nael

Reputation: 1507

Nginx append a trailing slash to the url

I am having an issue in Safari and IE where a django redirect does not include the authorization headers. This leads to the requests being rejected.

These redirects happen with the URL does not end with a /.

So I am trying to handle adding the / in the nginx config before it is passed to the app.

Here is my nginx config:

server {
  server_name ~^((stage|prod)-)?chalktalk-react-40.*;

  listen 28000 default_server;

  location ~ ^/static/(?P<file>.*) {
    root /chalktalk/var/chalktalk-react-40;
    add_header 'Access-Control-Allow-Origin' $cors_origin;

    # Inform downstream caches to take certain headers into account when reading/writing to cache.
    add_header 'Vary' 'Accept-Encoding,Origin';

    try_files /staticfiles/$file =404;
  }

  location ~ ^/media/(?P<file>.*) {
    root /chalktalk/var/chalktalk-react-40;
    try_files /media/$file =404;
  }

  location / {
    if ($request_uri ~ ^([^.\?]*[^/])$) {
        return 301 $1/;
    }

  }
  # API endpoints have their own authentication and authorization
  # schemes, so we bypass basic auth.
  location ~ ^/(api|admin|ws)/ {
    try_files $uri @proxy_to_app;
  }


  rewrite ^(.*)/favicon.ico$ /static/pages/homepage/logo-nonname.png last;

  location @proxy_to_app {
        proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
    proxy_set_header X-Forwarded-Port $http_x_forwarded_port;
    proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_set_header Host $http_host;
    proxy_read_timeout 1200;
    proxy_redirect off;


    proxy_pass http://chalktalk-react-40_app_server;

      }


  # Forward to HTTPS if we're an HTTP request...
  if ($http_x_forwarded_proto = "http") {
    set $do_redirect "true";
  }

  # Run our actual redirect...
  if ($do_redirect = "true") {
    rewrite ^ https://$host$request_uri? permanent;
  }

  } 

I know I have to add a rewrite and this is the rewrite I am trying to add:

server {
  ...
  listen 28000 default_server;
  rewrite ^([^.]*[^/])$ $1/ permanent;
  ...
}

The issue that I have with that is when I try to visit: example.com/admin, I get example.com:28000/admin/.

How do i make sure it leads to this example.com/admin/ without the port # inserted there?

UPDATE: I updated the config to have the following:

server {
  server_name ~^((stage|prod)-)?chalktalk-react-40.*;

  listen 28000 default_server;
  port_in_redirect off;
  rewrite ^([^.]*[^/])$ $1/ permanent;
  ...
}

But I get this error in Safari: enter image description here

Upvotes: 1

Views: 4382

Answers (1)

Richard Smith
Richard Smith

Reputation: 49792

Use either the port_in_redirect directive, for example:

port_in_redirect off;

Or tell Nginx exactly what you want in the rewrite directive, for example:

rewrite ^([^.]*[^/])$ $scheme://$host$1/ permanent;

Upvotes: 3

Related Questions