LeoXela
LeoXela

Reputation: 63

Nginx redirect based on referring URL regular expressions

New to nginx and still trying to figure out its methods.

I'm trying to do a redirect to an external URL based on the referring URL. For example, in the code below that I have for the hosted domain, if the referring URL comes from Facebook, I want to redirect the user to a specific URL:

location / {
index index.php;
    if ($http_referer ~* ^(.*?(\bfacebook\b)[^$]*)$ ) {
           rewrite http://www.othersite.com break;
    } 
try_files $uri $uri/ @handler;
expires 30d; 
}  

Nginx doesn't throw any errors once it's restarted, but despite testing this from a Facebook link, it's not executing.

Any nginx / regular expression gurus who can point me in the right direction?

Thanks in advance.

Upvotes: 1

Views: 2381

Answers (1)

Richard Smith
Richard Smith

Reputation: 49812

Although it may pass the syntax test, your rewrite statement is incorrect. To redirect any URI to a new URL you would use:

rewrite ^ http://www.example.com/? permanent;

But the preferred solution would be the more efficient:

return 301 http://www.example.com/;

See this page for details of both directives.

Upvotes: 1

Related Questions