Nginx rewrite rule that includes a blank spce with Plus Sign

Saturday, April 28, 2018

Nginx rewrite rule that includes a blank spce with Plus Sign :-

f you would like to remove spaces from a URL and then redirect to the stripped URL without the spaces simply use the following to catch all URLs with the issue:

rewrite ^(.*)(\s|%20)(.*)$ $1$3 permanent; # to redirect permanent
rewrite ^(.*)(\s|%20)(.*)$ $1$3 break; # to without redirect

This is basically grabbing everything before the first occurrence of a space \s or a URL encoded space %20 in capture group 1 ($1). The spaces are then captured in group 2 ($2). Then finally anything left over past group 2 is captured in group 3 ($3). I then join capture groups 1 and 3 together ($1$3) to form the redirect URL without the spaces in capture group 2 ($2).

This will work with a URL with multiple spaces throughout the URL, but it is working one at a time. So the URL with 2 spaces in it, will then redirect to the URL with 1 space and then finally to URL with no spaces.

You can of course change the redirect type from permanent if you wish. This will currently redirect with a 301 code.

to replace 2, 3, 4 spaces use below rewrite rule. but this is not recommended. 

rewrite ^(.*)(\s|%20)(.*)(\s|%20)(.*)$ $1$3&5 break;
rewrite ^(.*)(\s|%20)(.*)(\s|%20)(.*)(\s|%20)(.*)$ $1$3$5$7 break;
rewrite ^(.*)(\s|%20)(.*)(\s|%20)(.*)(\s|%20)(.*)(\s|%20)(.*)$ $1$3$5$7$9 break;

0 comments:

About This Blog

Lorem Ipsum

  © Copyright 2009 Linux-HelpLine.Blogspot.com

Back to TOP