legendary_rob
legendary_rob

Reputation: 13002

Nginx rewrite not redirecting

I would like to rebuild a URL and redirect from https://test.com/info/schoolName/detail to https://test.com/school-info?name=schoolName with Nginx.

I have tried

location ~ ^/(school-info)(?:/(.*))?$ {
  include /etc/nginx/servers/platform/shared/headers_proxy.conf;

  proxy_set_header Host $backend_netlify_main;
  proxy_ssl_server_name on;

  proxy_pass https://$backend_netlify_main/$1/$2;
}

...
...

location ~* ^/(info|info/)$ {
  include /etc/nginx/servers/platform/shared/headers_proxy.conf;

  rewrite ^/info/(.?)/(.*)$ /school-info?school=$1 permanent;

  proxy_pass $backend_cms;
}

however, if I visit https://test.com/info/byu/detail it's not doing a redirect at all.

EDIT: The /detail at the end is not important at all, so regardless of what is at the end of the URL the /schoolName/ is the most important part to be passed as a query parameter.

Upvotes: 0

Views: 154

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15478

I think you need something like

location / { # "default" location
    # do redirection for '/info/...' URIs
    rewrite ^/info/([^/])* /school-info/$1 permanent;
    # otherwise pass request to the default backend
    proxy_pass $backend_cms;
}
location /school-info {
  include /etc/nginx/servers/platform/shared/headers_proxy.conf;

  proxy_set_header Host $backend_netlify_main;
  proxy_ssl_server_name on;

  proxy_pass https://$backend_netlify_main;
}

if you need to pass a request as /school-info/schoolName, or

location / { # "default" location
    # do redirection for '/info/...' URIs
    rewrite ^/info/([^/])* /school-info?name=$1 permanent;
    # otherwise pass request to the default backend
    proxy_pass $backend_cms;
}
location /school-info {
  include /etc/nginx/servers/platform/shared/headers_proxy.conf;

  proxy_set_header Host $backend_netlify_main;
  proxy_ssl_server_name on;

  proxy_pass https://$backend_netlify_main/school-info$is_args$args;
}

if you need to pass a request as /school-info?name=schoolName.

Upvotes: 1

Related Questions