简体   繁体   中英

How to implement rewrite in nginx based on existence of a specific argument in the URI?

Original Goal: I wanted users trying to open page http://example.com/something to get redirected to http://example.com/index.php?download=something

Original Goal Example: Users coming to Source URL ( http://something.com/18AhPyB&p=CdATyJnFMw1gl9Z ) got redirected to Destination URL ( http://something.com/index.php?download=18AhPyB&p=CdATyJnFMw1gl9Z )

Things I did in my Nginx Config :

location / {
rewrite ^/(.*)$ /index.php?download=$1 last; }

Problem With The Approach: If someone is trying to open homepage ( http://something.com ) its giving error. My understanding is unintentionally I made all calls to get redirected.

Question: How I do make urls only with "&p" parameter to get redirected? Pl help.

^\/(.*&p=.*)$
  • ^ is the string start.
  • \\/ is the character / escaped.
  • () the captured group.
  • .* matches any character with unlimited length.
  • &p= matches &p= literally.
  • $ is the string end.

Regex101 ( here ) is great for creating and debugging regular expressions.

As I understand, you have to redirect only if the parameter download is present. Then yo have to write a location section like this:

index index.php;
location / {
    try_files $uri $uri/ /index.php;

    if ($arg_p) {
        return 301 http://something.com/index.php?download=$request_uri;
    }

    location = /index.php {

        fastcgi_pass   127.0.0.1:6969;
        fastcgi_param  SCRIPT_FILENAME /var/www$fastcgi_script_name;
        include        fastcgi_params;
    }
}

Remember to change the port to your php-fpm or whatever yo use to process your php code.

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