convert .htaccess for nginx

António P. P. Almeida appa at
Sun Feb 6 22:30:31 MSK 2011

On 6 Fev 2011 19h10 WET, nginx-forum at wrote:

> Hello, I have tryed to read about rewrite rules but I'm not able to
> handle this, Have already tryed online convert for .htaccess to
> nginx but when I restart my ngnix server I get error message [code]
> [emerg]: invalid parameter "/[L]" in
> /usr/local/nginx/conf/rrulesvco:24 configuration file
> /usr/local/nginx/conf/nginx.conf test failed [/code]
> /usr/local/nginx/conf/rrulesvco is include in my nginx.conf file
> under my "location ~ \.php$ { "
> My old .htaccess looks like so:
> [code] RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D)
> [OR] RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
> RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
> RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
> RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
> RewriteRule ^([^.]*)/?$ index.php [L] RewriteRule
> ^videos/(.*)/(.*)/(.*)/(.*)/(.*)
> videos.php?cat=$1&sort=$3&time=$4&page=$5&seo_cat_name=$2 [L]
> RewriteRule ^videos videos.php?%{QUERY_STRING} [L] RewriteRule
> ^video/(.*)/(.*) watch_video.php?v=$1&%{QUERY_STRING} [L]
> RewriteRule ^channels/(.*)/(.*)/(.*)/(.*)/(.*)
> channels.php?cat=$1&sort=$3&time=$4&page=$5&seo_cat_name=$2 [L]
> RewriteRule ^channels channels.php [L] RewriteRule
> ^group/([a-zA-Z0-9].+) view_group.php?url=$1&%{QUERY_STRING} [L]
> RewriteRule ^view_topic/([a-zA-Z0-9].+)_tid_([0-9]+)
> view_topic.php?tid=$2&%{QUERY_STRING} [L] RewriteRule
> ^groups/(.*)/(.*)/(.*)/(.*)/(.*)
> groups.php?cat=$1&sort=$3&time=$4&page=$5&seo_cat_name=$2 [L]
> RewriteRule ^groups groups.php [L] RewriteRule ^create_group
> create_group.php [L] RewriteRule ^sitemap.xml$ sitemap.php
> RewriteRule ^signup signup.php RewriteRule ^rss$ rss.php [nc]
> RewriteRule ^rss/([a-zA-Z0-9].+)$ rss.php?mode=$1&%{QUERY_STRING}
> [nc] RewriteRule ^desktop desktop.php [L]

Have read the documentation at the wiki?

Is shock full of examples.

Bear in mind that:

1. There's no RewriteCond equivalent in Nginx. Instead you match a
   given location and the rewrite happens there.

2. Apart from the fact that Apache uses a more verbose syntax the
   Rewrite rule can be sort of copied from Apache to Nginx. 

3. Flags, Apache - Nginx equivalence:

   L - last 
   R=301 - permanent
   R=302 or simply R - redirect
Here's an example from your Apache rewrites:

1. Without condition:

RewriteRule ^channels/(.*)/(.*)/(.*)/(.*)/(.*) channels.php?cat=$1&sort=$3&time=$4&page=$5&seo_cat_name=$2 [L]

rewrite ^channels/(.*)/(.*)/(.*)/(.*)/(.*) channels.php?cat=$1&sort=$3&time=$4&page=$5&seo_cat_name=$2  last;

2. With a condition:

if ($query_string ~ "base64_encode.*\(.*\)") {
  rewrite ^(?:[^.]*)/?$ index.php last;

Now you just have to do it for every other condition and rule in your
Apache config.

--- appa

More information about the nginx mailing list