0

I would like to add en-us language code on URL. The expectation is as follows.

When a user hits on http://example.com/, page should redirect users to http://example.com/en-us/ Note: I have achieved this with the following code.

location = / {
      rewrite ^ /en-us/ redirect;
  }

How to redirect customers to following scenarios

Simply, what i want to achieve is if there is no en-us in url, then we should add en-us in XX-XX place. http://example.com/XX-XX/contact

Karthi Skb
  • 322
  • 4
  • 15

2 Answers2

1
# Do nothing for assets (paths with a dot)

location ~ \. {
}

You can match locations that don't start with the required path by using a negative lookahead regex (?!)

# Paths that don't start  with /en-us/ are redirected:

location ~ ^(?!/en-(us|in)/) {
    rewrite ^/(.*)$ /en-us/$1 redirect;
}

Or using an if block:

if ($request_uri !~ "^/en-(us|in)/")
{
    return 301 /en-us/$request_uri;
}
jspcal
  • 50,847
  • 7
  • 72
  • 76
  • Hi, thanks for your answer and its working well. I have added 1 more scenario (3rd point). Is it possible to restrict the url appending? – Karthi Skb Apr 30 '18 at 09:48
  • Yes, have the regexes include in as well. – jspcal Apr 30 '18 at 10:01
  • Thank you it's working as expected. But one more problem is coming, i don't want to append this language code in js and css urls. It results, the page is not rendering properly. I want this redirect to work only for website URLs, not static files. It will be great if we have the option like that. – Karthi Skb Apr 30 '18 at 11:12
  • You can match against static assets and have an empty block – jspcal Apr 30 '18 at 11:28
0

Did you read the rewrite documentation? There are many similar examples there.

This is I'd do that (untested).

# Do not redirect /
location = / {
}

# Redirect everything else to /en-us/...
location / {
    rewrite ^/(.*)$ /en-us/$1 redirect;
}
ntd
  • 7,372
  • 1
  • 27
  • 44