Kokizzu
Kokizzu

Reputation: 26838

Convert Rewrite Rule Prefix Matching from Apache to Nginx

How to convert Apache's prefix matching to Nginx?

RewriteCond %{REQUEST_URI} ^/test1
RewriteRule ^(.*)$ http://newsite/$1 [R=301,L]

RewriteCond %{REQUEST_URI} ^/foo
RewriteRule ^(.*)$ http://newsite/$1 [R=301,L]

RewriteCond %{REQUEST_URI} ^/bar
RewriteRule ^(.*)$ http://newsite/$1 [R=301,L]

Or

RewriteRule ^/test1/(.*)$ http://newsite/test1/$1 [R=301,L]
RewriteRule ^/foo/(.*)$ http://newsite/foo/$1 [R=301,L]
RewriteRule ^/bar/(.*)$ http://newsite/bar/$1 [R=301,L]

Is it something like this?

location / {
   rewrite ^/(test1|foo|bar)/(.*)$   http://newsite/$1/$2 permanent;
   ...
}

Upvotes: 1

Views: 97

Answers (1)

grochmal
grochmal

Reputation: 3027

Your rewrite is not bad. It will work. The only thing is that people prefer the return directive in nginx because it is a little faster (nginx needs to do less processing).


I'm not very familiar with apache rewrites so i might be slightly wrong in my interpretation of them but i believe that you only want to rewrite URLs under /test1, /foo and /bar. For that purpose you do not even need the rewrite directive, you can make it with a simple return in nginx

location /test1 {
    return 301 http://newsite$request_uri;
}
location /foo {
    return 301 http://newsite$request_uri;
}
location /bar {
    return 301 http://newsite$request_uri;
}
location / {
    ...  # pages on this domain
}

Using a regex is a little slower:

location ~ /(test1|foo|bar) {
    return 301 http://newsite$request_uri;
}

And you can use a rewrite directive too, if you really want:

location ~ /(test1|foo|bar) {
    rewrite ^ http://newsite$request_uri permanent;
}

Upvotes: 1

Related Questions