Nginx如何从$ uri中删除前导斜杠

kur*_*sus 8 nginx

我的Nginx配置文件:

  location / {
    try_files $uri $uri/ /index.php?url=$uri;
  }

  ## PHP conf in case it's relevant 
  location ~ \.php$ {
  fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
  fastcgi_split_path_info ^(.+\.php)(/.*)$;
  include /etc/nginx/fastcgi.conf;
  fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
  }
Run Code Online (Sandbox Code Playgroud)

尝试以下网址http://example.org/login:

预期行为:

http://example.org/index.php?url=login

实际行为:

http://example.org/index.php?url=/login

Ric*_*ith 7

使用命名位置和内部重写.例如:

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^/(.*)$ /index.php?url=$1 last;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此文

  • “但是 nginx 和 Apache 在 URI 上的领先 / 上似乎有相反的政策。” - Apache 上的“策略差异”仅与 `RewriteRule` _pattern_ 匹配的 URL 路径有关,并且仅当在 _directory_(或 `.htaccess`)上下文中使用时(在 Nginx 上不存在)。当在 _server_(或 _virtualhost_)上下文中使用时,Apache 在这方面与 Nginx 相同。然后是 Apache `REQUEST_URI` 服务器变量,它始终包含完整的 URL 路径 - 与 Nginx `$uri` 相同。 (2认同)