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

时间:2016-08-31 12:25:54

标签: php nginx url-rewriting

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 (e.g. 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

2 个答案:

答案 0 :(得分:0)

你正在寻找类似的东西,

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

但事情并非如此简单。这会将任何网址与查询字符串和等号(不仅仅是i.php)重定向到site.com/everything_after_the_equal_sign。如果您只想将其应用于i.php,则需要为其创建一个位置块,例如。

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

如果您有这样的现有位置块,则需要添加此if语句。如果您从通用位置块(例如

)提供所有PHP内容
location ~ \.php$ {
    #your config here
}

然后您需要专门添加通用块上方的/i.php/

最重要的是

如果是邪恶的(请参阅here)。如果您在位置块中有if语句,这将适用于您。如果可以,请尝试重写代码以在内部执行这些重定向。否则,正如文档中所述,if有时是不可避免的。

我希望这会有所帮助。

答案 1 :(得分:0)

我通过使用它来实现它:

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