Nginx – help with nginx rewrite

nginxrewrite

In an apache setup I was masking the wordpress behind the url /admin.

I accomplished this with the following rules:

RewriteRule admin/(.*).php wordpress/wp-admin/$1.php [L]
RewriteRule /admin$ admin/ [L,R=301]
RewriteRule ^admin/$ wordpress/wp-admin/index.php [L]

So the last rule was pretty easy with nginx:

rewrite ^/admin/$ /wordpress/wp-admin/index.php last;

More or less a word for word repeat.

The second rule doesn't seem to be necessary…it was only there to force a slash at the end.

The first rule doesn't seem to be picking up. I'm having nginx output debugging information for rewrites, and it doesn't seem to write anything there for urls like /admin/edit.php

Here is my entire nginx config, if there would be some nuggets of information there:

worker_processes  1;
events {
    worker_connections  1024;
}

error_log    /var/log/file.log notice;

http {
    rewrite_log  on;
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {
       listen       80;
       server_name  localhost;

       location / {
        root   /home/meul/site/htdocs/web;
        index  index.php index.html index.htm;

        if (-f $request_filename) {
          expires max; 
          break; 
        }

        rewrite ^/admin/(.*).php$  /wordpress/wp-admin/$1.php break;
        rewrite ^/admin/$ /wordpress/wp-admin/index.php last;

        if ($request_filename !~ "\.(js|htc|ico|gif|jpg|png|css)$") {
          rewrite ^(.*) /index.php last;
        }
    }



    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/www/nginx-dist;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /home/meul/site/htdocs/web$fastcgi_script_name;
        include        fastcgi_params;
    }


}

Best Answer

Change

rewrite ^/admin/(.*).php$  /wordpress/wp-admin/$1.php break;

to

rewrite ^/admin/(.*)\.php$  /wordpress/wp-admin/$1.php last;

break stops processing after the current location block, but in this case you still need the location ~ \.php$ block to serve the admin php. Also, because this is a regex, you want to escape the literal . before the php extension.