用于重写规则的Nginx配置

时间:2018-01-17 20:02:03

标签: nginx url-rewriting

所以我现在在nginx中有这个配置:

autoindex off;

        location / {
            try_files $uri $uri.html $uri/ @extensionless-php;
            index index.html index.htm index.php;
        }

        location @extensionless-php {
                rewrite ^(.*)$ $1.php last;
        }

        # pass PHP scripts to FastCGI server
        #
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;

                # With php-fpm (or other unix sockets):
                fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
                # With php-cgi (or other tcp sockets):
                #fastcgi_pass 127.0.0.1:9000;
        }

现在,我希望获得“特别”的东西。我想将一个网址(http://project2.local/camera?camera_id=1)重写为http://project2.local/camera/1我已尝试过此代码;

location / {
  rewrite ^/?camera\.php$ /camera/%1? redirect;
}

location /camera {
  rewrite ^/camera/([^/]*)$ /camera.php?camera_id=$1 break;
}

但是当我导航到那个地方时会下载一些空的东西..我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试:

location /camera {
    rewrite ^/camera/([^/]*)$ /camera.php?camera_id=$1 last;
}

rewrite...break将阻止PHP位置处理camera.php URI。您需要根据现有配置使用last。有关详细信息,请参阅this document

您还添加了location / { rewrite ^/?camera\.php$ /camera/%1? redirect; },但由于多种原因,这似乎是错误和多余的:

  • 您不能拥有两个location /块(也许您的意思是您已将代码行添加到现有location /块中)

  • 我无法识别%1字词(参数的值为$arg_camera_id

  • 永远不会匹配任何内容(以.php结尾的URI由PHP位置处理)