Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx URL rewrite using negative regex?

Tags:

regex

nginx

I'm trying to redirect requests to https in nginx, unless it is of the form HOST/ANY_STRING_OF_CHARS/END_OF_URI, e.g.:

http://host.org/about # no redirect

http://host.org/users/sign_in # redirects to https://host.org/users/sign_in

This apparently works in Apache, but I don't understand how the bang works (ignore if it doesn't really work):

RewriteRule !/([a-z]+)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

How can I do this in a nginx rewrite rule? This is not working as I'd hoped:

rewrite !/([a-z]+)$ https://$server_name$request_uri redirect;

This doesn't do the redirect either, in case I had the logic backwards:

rewrite /([a-z]+)$ https://$server_name$request_uri redirect;

Help please?

like image 754
kbighorse Avatar asked Apr 23 '13 00:04

kbighorse


People also ask

How do I change my URL in nginx?

NGINX Return directive The easiest and cleaner way to rewrite an URL can be done by using the return directive. The return directive must be declared in the server or location context by specifying the URL to be redirected.

What is return 301 in nginx?

Permanent redirects such as NGINX 301 Redirect simply makes the browser forget the old address entirely and prevents it from attempting to access that address anymore. These redirects are very useful if your content has been permanently moved to a new location, like when you change domain names or servers.

What is rewrite rule in nginx?

Rewrite rules modify a part or whole of the URL. This is done for two reasons. First, to inform clients about the relocation of resources, and second, to control the flow to Nginx. The two general-purpose methods used widely for rewriting URLs are the return directive and the rewrite directive.


2 Answers

Sends a permanent redirect to the client:

server {
  listen 80;
  rewrite ^(/users/\w+)$ https://$host$1 permanent;
  ...
}

for negative match you could use:

if ($request_uri !~ "^/users/\w+$")
{
  return 301 https://$host$request_uri;
}
like image 200
Jack Avatar answered Sep 20 '22 05:09

Jack


set $test "0";
if ($request_uri ~ "condition") {
   set $test "1";
}
if ($test ~ "0") {
   return 301 redirect url;
}
like image 39
Sergiy Tytarenko Avatar answered Sep 18 '22 05:09

Sergiy Tytarenko