简体   繁体   中英

Nginx configuration for rewrite rule

So I have this configuration at the moment in nginx:

autoindex off;

        location / {
            try_files $uri $uri.html $uri/ @extensionless-php;
            index index.html index.htm index.php;
        }

        location @extensionless-php {
                rewrite ^(.*)$ $1.php last;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;

                # With php-fpm (or other unix sockets):
                fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
                # With php-cgi (or other tcp sockets):
                #fastcgi_pass 127.0.0.1:9000;
        }

Now, I want to get something 'special'. I want to get an url ( http://project2.local/camera?camera_id=1 ) to be rewritten as http://project2.local/camera/1 I've tried this code;

location / {
  rewrite ^/?camera\.php$ /camera/%1? redirect;
}

location /camera {
  rewrite ^/camera/([^/]*)$ /camera.php?camera_id=$1 break;
}

but that downloads something empty when I navigate to that place.. What am I doing wrong here?

Try:

location /camera {
    rewrite ^/camera/([^/]*)$ /camera.php?camera_id=$1 last;
}

The rewrite...break will prevent the camera.php URI being processed by the PHP location. You need to use last as per your existing configuration. See this document for details.

You also added: location / { rewrite ^/?camera\\.php$ /camera/%1? redirect; } location / { rewrite ^/?camera\\.php$ /camera/%1? redirect; } location / { rewrite ^/?camera\\.php$ /camera/%1? redirect; } , but it seems wrong and superfluous for a number of reasons:

  • You cannot have two location / blocks (perhaps you meant you added the line of code to the existing location / block)

  • I do not recognise the %1 term (the value of the parameter would be $arg_camera_id )

  • It will never match anything (URIs ending with .php are processed by the PHP location)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM