简体   繁体   中英

Nginx rewriteurl from example.com/script.php?param=value to example.com/value

I have a PHP script that accepts a single parameter.

My project structure is like the following:

index.php
i.php
terms.php
functions
includes
icons
resources

The script that I want to rewrite its URL is i.php from

example.com/i.php?icon=id

to

example.com/id

While making sure everything else is normally accessible (eg example.com/terms.php ).

How do I do that?

Edit This might be helpful. Here's my previous .htaccess that I used to use on my apache server:

Options +FollowSymLinks  
RewriteEngine On  

RewriteCond %{SCRIPT_FILENAME} !-d  
RewriteCond %{SCRIPT_FILENAME} !-f  
RewriteRule ^(\w+)$ ./i.php?icon=$1

You're looking for something like,

if ($query_string ~ .*=(.*)){ 
    return 301 $scheme://site.com/$1;
} 

but it's not that simple. This will redirect any URL with a query string and an equal sign (not just i.php ) to site.com/everything_after_the_equal_sign . If you only want this to apply to i.php , you'll need to create a location block for it eg.

location /i.php/ {
    if ($query_string ~ .*=(.*)){ 
    return 301 $scheme://site.com/$1;
}

If you have an existing location block like this, then this if statement needs to be added. If you're serving all PHP content from a generic location block such as

location ~ \.php$ {
    #your config here
}

then you'll need to specifically add the /i.php/ above the generic block.

Most importantly :

if is evil (see here ). This will apply to you if you have the if statement in the location block. If you can, try to rewrite your code to do these redirects internally. Otherwise, as stated in the docs, if is sometimes unavoidable.

I hope this helps.

I've got it working by using this:

location / {
    try_files $uri $uri/ /i.php?icon=$uri;
}

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