Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx redirect rule has no affect

Trying to do a simple redirect:

rewrite https://url.example.com(.*) https://example.com/plugins/url permanent;

Anytime url.example.com is hit, I want it to redirect to that specific path.

EDIT:

Will try to explain this better, as I'm trying to redirect to a specific domain from another.

server {
    server_name example.com plugin.example.com;
    root /home/www/example.com/public;
}

I see the location used for redirects such as:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

But not sure how to use it in my case, which is to change plugin.example.com to example.com/plugin.

For example:

http://plugin.example.com
https://plugin.example.com
https://plugin.example.com/blah
https://plugin.example.com/blah/more

All of these should redirect to:

https://example.com/plugin
like image 252
Rob Avatar asked Jun 08 '19 04:06

Rob


People also ask

How do I create a temporary and permanent redirect with nginx?

In Nginx, you can accomplish most redirects with the built-in rewrite directive. This directive is available by default on a fresh Nginx installation and can be used to create both temporary and permanent redirects. In its simplest form, it takes at least two arguments: the old URL and the new URL.

What is $scheme in nginx?

The rewritten URL uses two NGINX variables to capture and replicate values from the original request URL: $scheme is the protocol (http or https) and $request_uri is the full URI including arguments. For a code in the 3xx series, the url parameter defines the new (rewritten) URL.


1 Answers

If the original URL is https://url.example.com or https://url.example.com/ then the normalized URI used by the rewrite and location directives will be /. The scheme, host name and query string have all been removed.

To perform a permanent redirect to a URL with a different host name:

Using rewrite (see this document for details):

rewrite ^/$ https://example.com/foo permanent;

Or using location and return (see this document for details):

location = / {
    return 301 https://example.com/foo;
}

The second solution is more efficient, as there are no regular expressions to process.

If the original URL includes a query string: The rewrite will append it automatically unless a trailing ? is added. The return will not, but can be added by appending $is_args$args.


If the scheme and host name are unchanged, then both statements can be simplified:

rewrite ^/$ /foo permanent;

Or:

location = / {
    return 301 /foo;
}
like image 134
Richard Smith Avatar answered Sep 22 '22 11:09

Richard Smith