带GET参数的Nginx 301重定向配置及特定场景实现咨询
Hey there! Let's break down how to handle 301 redirects when GET parameters are present in Nginx, including your specific use case.
1. General Approach: Redirect Any URL with GET Params to the Parameter-Free Version
If you want a broad rule that redirects any URL on your domain that has GET parameters to the same path without the params, you can use Nginx's built-in $args variable to check for existing parameters.
Here's a simple configuration you can add to your server block:
server { listen 80; server_name mysite.com; # Redirect any URL with GET params to the same path without params if ($args) { # $uri holds the request path (without params) — preserves trailing slashes return 301 $uri; } }
Notes:
$argscontains all the GET parameters from the request. If it's not empty, the condition triggers.return 301sends a permanent redirect response, which is ideal for SEO.- This rule applies to all URLs on the server. If you only want it for specific paths, wrap it in a
locationblock instead.
2. Specific Use Case: Redirect mysite.com/blablabla/efefefe.html/?Param_a=1 to the Parameter-Free Path
For your exact scenario, you can create a targeted rule to only affect this specific URL (or path) instead of applying a broad rule. Here are two options:
Option 1: Exact Match for the Path and Specific Parameter
If you only want to redirect when the parameter is exactly Param_a=1, use this configuration:
server { listen 80; server_name mysite.com; # Exact match for the target path location = /blablabla/efefefe.html/ { # Check if the params are exactly "Param_a=1" if ($args ~* "^Param_a=1$") { return 301 $uri; } } }
Option 2: Remove All Parameters for This Specific Path
If you want to strip any GET parameters from this path (not just Param_a=1), simplify the condition:
server { listen 80; server_name mysite.com; location = /blablabla/efefefe.html/ { if ($args) { return 301 $uri; } } }
Alternative: Using rewrite Instead of if
Some prefer using rewrite for more granular regex control. Here's an equivalent rule using rewrite:
server { listen 80; server_name mysite.com; rewrite ^/blablabla/efefefe.html/\?(.*)$ /blablabla/efefefe.html/ permanent; }
The permanent flag tells Nginx to send a 301 redirect, and the regex matches any parameters after the ? in the target path.
内容的提问来源于stack exchange,提问作者Max Siratskyi

