【问题标题】:Nginx configuration for rewrite rule重写规则的 Nginx 配置
【发布时间】:2018-01-18 06:46:29
【问题描述】:

所以我现在在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;
        }

现在,我想要一些“特别”的东西。我想获取一个 url (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;
}

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

【问题讨论】:

    标签: nginx url-rewriting


    【解决方案1】:

    试试:

    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 位置处理)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-30
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      相关资源
      最近更新 更多