在Nginx中重写URI

时间:2011-07-03 22:00:43

标签: url-rewriting nginx

我试图为我的框架设置URI路由并且我当前正在使用nginx作为服务器,但问题是我在尝试访问以下任一链接时仍然遇到500错误

  • http://localhost.framework/
  • http://localhost.framework/index.php/

如果我使用以下链接访问该网站,则可以使用:

  • http://localhost.framework/index.php
  • http://localhost.framework/index.php?/

我对域的配置如下:

server {
    listen 80;
    server_name localhost.framework;
    root   /var/www/ASFramework;

    access_log  /var/log/nginx/framework.access.log;
    error_log  /var/log/nginx/framework.error.log;

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

        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_index  index.php;
        include        fastcgi_params;
                fastcgi_param  SCRIPT_FILENAME  /var/www/ASFramework$fastcgi_script_name;
        }
}

基本上我试图做的是采取以下网址

  • http://localhost.framework/controller/method/../

并将其重写为:

  • http://localhost.framework/index.php/controller/method/../

在日志中(error.log)是:

2011/07/03 22:57:22 [error] 19837#0: *6 rewrite or internal redirection cycle while processing "/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/", client: 127.0.0.1, server: localhost.framework, request: "GET / HTTP/1.1", host: "localhost.framework"

有人能告诉我发生了什么以及如何解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

更改此行:

location ~ \.php$ {

进入这个:

location ~ \.php.*$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  /var/www/ASFramework$fastcgi_script_name;
}

答案 1 :(得分:2)

您的重写规则会导致重定向周期。 nginx index.php递归替换index.php/index.php。因此,在第二次替换后,您的新网址将为index.php/index.php/index.php,依此类推。

你可能想要这样的东西:

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

index.php?action=someaction重写为/someaction

答案 2 :(得分:0)

试试这个:

location / {
    if ($request_uri !~ "/(index\.php)") {
        rewrite ^/(.*)$ /index.php/$1 last;
    }
}