Rewrite code from htaccess to nginx config?

2019-06-23 22:52发布

问题:

I have problem with implement my rewrite code from htaccess file into nginx config. I've already tried generator : http://winginx.com/htaccess for generate my rewrite code.

My nginx config code:

server {
        listen 80;
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;       
}

server {
        listen 80;
        root /usr/share/nginx/www;
        index index.php;
        server_name www.example.com;
        error_page 404 http://www.example.com/404.php;
        autoindex off;
        error_log  /usr/share/nginx/www/nginx_error.log  warn;

   location / {
        rewrite ^([^\.]*)$ /$1.php;
    }

    location = / {
        rewrite ^ /index.php;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

}

I wanna implement this from my .htaccess:

RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-/_]+)$ admin/index.php?hotelname=$1&do=$2 [QSA]
RewriteRule ^(([A-Za-z0-9-/]+)+)$ admin/index.php?hotelname=$1 [L]

Generated code from tool:

location / {
  rewrite ^/([A-Za-z0-9-]+)/([A-Za-z0-9-/_]+)$ /admin/index.php?hotelname=$1&do=$2;
  rewrite ^/(([A-Za-z0-9-/]+)+)$ /admin/index.php?hotelname=$1 break;
}

I have alredy tried implement this last lines of code to my location blocks but not working at all.. I will be very greateful for every opinion! Regards Makromat

回答1:

The blind kind of conversion would be

rewrite ^([A-Za-z0-9-]+)/([A-Za-z0-9-/_]+)$ admin/index.php?hotelname=$1&do=$2&$query_string last;
rewrite ^(([A-Za-z0-9-/]+)+)$ admin/index.php?hotelname=$1 last;

But I would prefer if I understand the question more to produce a more optimum rewrite.

When do I know if the URL should be passed to /admin or not, give me an actual URI for backend and for frontend.



回答2:

Usually rewrites are better managed in nginx using nginx way of thinking. And this new way of thinking is more based on try_file.

So you may try something like that (untested):

location ^~ "/([A-Za-z0-9-]+)/([A-Za-z0-9-/_]+)"  {
    try_files $uri admin/index.php?hotelname=$1&do=$2&$args;
}
location ^~ "(([A-Za-z0-9-/]+)+)" {
    try_files $uri /admin/index.php?hotelname=$1;
}
location = / {
    rewrite ^ /index.php;
}
location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}

If direct access on given $urishould never happen, then remove that part from the try_files. Now I'm also unsure of your second regex (([A-Za-z0-9-/]+)+), why not using:

location ^~ "/([A-Za-z0-9-/])+"

Or

location ^~ "/([A-Za-z0-9-])+/"

So there's maybe something I do not see, even in your apache rewrites.