3

I am trying to add a simple rule to my NGINX configuration whereby the root url www.example.com is always rewritten with a language suffix www.example.com/en/. I have tried this:

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

    location / {
        rewrite ^$ www.example.com/en/ permanent;
    }

    ...
}

But no luck. Where am I going wrong? Also, is it possible to have a condition where NGINX checks if there is an/en/ suffix and if not, adds one?

EDIT

So I was only one character away from what I wanted initially:

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

    location / {
        # needed the / in between the anchor tags
        rewrite ^/$ www.example.com/en/ permanent;
    }

    ...
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Darwin Tech
  • 18,449
  • 38
  • 112
  • 187
  • You could use the [accept language module](http://Accept%20language%20module%20is%20your%20friend). Also, this [question](http://stackoverflow.com/questions/3657614/how-to-rewrite-location-in-nginx-depending-on-the-client-browsers-language) looks very similar to yours – danielgpm Mar 11 '16 at 21:14
  • I don't think I need to use the language module. My priority is just rewriting the root url `/` to `/en/`. For the time being I'm happy that any url without the suffix returns a 404. – Darwin Tech Mar 11 '16 at 22:36
  • In the answer that I linked the are examples on how to do exactly that. – danielgpm Mar 11 '16 at 22:53
  • The answer to the first part of my question was very simple - just needed the `/` inbetween the `^` and `$` anchors. – Darwin Tech Mar 11 '16 at 23:02
  • Does `location / { ... }` not indicate that? – Darwin Tech Mar 11 '16 at 23:15
  • Also, repeating the server value is not a good practice, you could just use $server_name variable. that way will be reusable on other locations if needed or better yet avoid using it at all: `rewrite (.*) $uri/en;` – danielgpm Mar 11 '16 at 23:16

1 Answers1

4

There are two normal ways to deal with redirects:

Using a rewrite rule

server {
    ...
    rewrite ^/$ /en/ permanent;    
    ...
}

Note that rewrite rules do not need to be absolute urls, but if they are to be absolute urls they need to include the protocol rewrite /x https://example.com/y;.

There is no need to put rewrite rules like this in a location block.

Using a location block + return 30x

Using a location block requires using an exact match for the url:

server {
    ...
    location = / {
        return 301 /en/;
    }
    ...
}

The use of = means the rule will only match requests for the root of the domain, otherwise the rules of location block precedence mean that the location block would be the default for all requests. Return is used to issue a 301 (permanent) redirect.

Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • 1
    For simplicity, if you are redirecting to the same scheme and host, you can omit both and just do `return 301 /en/;` – Roman Mar 12 '16 at 17:27