Nginx rewrite rule for cms backend

2019-07-04 09:35发布

问题:

I need to make url rewrite rules (server blocks) in nginx server same like in my previous apache server.
This is code from .htaccess what I need to implement (convert) into my existing one:

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]

This code is in my website because I need to hide in adress bar folder(/admin/) where is located files after login. And when somebody is already login, adress bar is like www.domain.com/username and when you click to menu adress is like www.domain.com/username/page1, www.domain.com/username/page2, www.domain.com/username/page3. This is what I need to achive in nginx. Because now is complete backend without function. When I login to backend, I'm redirected to www.domain.com/username but on screen I can see only File not found. In backend working only when I manualy add www.domain.com/admin/index.php.

This is my actual config for nginx :

server_names_hash_bucket_size  64;

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;



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

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


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

    location ~ /\.ht {
            deny all;
      }
}

When I try to change my block to:

location / {
        rewrite ^([^\.]*)$ /$1.php;
        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;
    }

Each my css file have error 500...

I will be very grateful with any help! Thanks a lot.

回答1:

You are putting this in your / location, that means that all your requests not matched before you drop here. You have to create a location role specific for this entry before the location /

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