如果只有 GET 请求,Nginx 重定向

Nginx Redirect if GET request only

我在 nginx 中有一个重定向(如果没有则添加尾部斜杠),我只想 运行 GET 请求以维护 POST 数据。检查 if is evil 文章似乎这个设置没问题?:

location / {
  if ($request_method = GET) {
    rewrite ^([^.]*[^/])$ / permanent;
  }
  try_files $uri $uri/ /index.php?$query_string;
}

然而,在实际加载内容之前,这条规则似乎让我在每次请求时都遇到 404 错误(我猜是因为我的 404 处理程序也经过了 index.php?)。这是一个 Craft CMS 站点。

这似乎不是重定向部分的问题,这工作正常(如果我没有斜线它重定向)当尾部斜线被击中时 404 发生,所以我认为它与try_files 有什么地方不对?然而,奇怪的是,如果我注释掉整个 if 语句(所以它只是 运行s try_files)我 得到 404.

如果这对配置中的其余位置块等有帮助(这些都遵循上面显示的 location / 块)

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/mysite.com-error.log error;

error_page 404 /index.php;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

location ~* \.(css|js|gif|png|ico|svg)$ {
    try_files $uri $uri/ /index.php?p=$uri&$args;
    expires 7d;
}

location ~* \.(jpg|jpeg)$ {
    expires 7d;
}

location ~ /\.ht {
    deny all;
}

location ~ /\.(?!well-known).* {
    deny all;
}

问题是 if 上下文处理所有 GET 请求。

假设 POST 请求应由 /index.php 处理,您可以使用 if 块来处理所有 POST 请求。

例如:

location / {
    if ($request_method = POST) {
        rewrite ^ /index.php last;
    }
    rewrite ^([^.]*[^/])$ / permanent;
    try_files $uri $uri/ /index.php?$query_string;
}