dpg76975
2016-08-31 12:25
浏览 48
已采纳

从example.com/script.php?param=value到example.com/value的Nginx重写

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

图片转代码服务由CSDN问答提供 功能建议

我有一个接受单个参数的PHP脚本。

我的项目 结构如下所示:

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

我要重写其URL的脚本是 i.php 来自

  example.com/i.php?icon  = ID 
   
 
 

 <代码> example.com/id
   \  n 
 

确保其他所有内容都可以正常访问(例如 example.com/terms.php )。

我该怎么做?< / p>

编辑 这可能会有所帮助。 这是我之前在我的apache服务器上使用的.htaccess:

  Options + FollowSymLinks 
RewriteEngine On 
 
RewriteCond%{SCRIPT_FILENAME}!-d 
RewriteCond%{  SCRIPT_FILENAME}!-f 
RewriteRule ^(\ w +)$ ./i.php?icon=$1
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongmin4990 2016-08-31 20:39
    已采纳

    I've got it working by using this:

    location / {
        try_files $uri $uri/ /i.php?icon=$uri;
    }
    
    点赞 打赏 评论
  • douyoupingji7238 2016-08-31 15:25

    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.

    点赞 打赏 评论