如何实现htaccess 301通配符重定向?URL路径变更需求
Hey there! Let's tackle this 301 wildcard redirect for your URL structure update—this is a super common scenario, and totally straightforward once you know the right rules for your web server. Below are solutions for the most popular server environments:
Apache (Using .htaccess)
If you're running Apache, you'll use the mod_rewrite module (make sure it's enabled on your server first). Add these lines to your root .htaccess file:
RewriteEngine On RewriteRule ^print-scan/(.*)$ /printing/$1 [R=301,L]
Breakdown:
RewriteEngine On: Enables the rewrite engine.^print-scan/(.*)$: Matches any URL that starts withprint-scan/, capturing everything after that in the(.*)group./printing/$1: Replaces the matched path withprinting/followed by the captured content from(.*).[R=301,L]: Sends a permanent 301 redirect response, andLtells Apache to stop processing further rewrite rules for this request.
Nginx
For Nginx, add this rewrite rule inside your server block in your Nginx configuration file (usually nginx.conf or a site-specific config in /etc/nginx/sites-available/):
server { # ... your existing server config (listen, server_name, root, etc.) ... rewrite ^/print-scan/(.*)$ /printing/$1 permanent; }
- The
permanentflag tells Nginx to send a 301 redirect, and the(.*)captures the rest of the path to append to the new URL.
IIS (Using web.config)
If you're on IIS, you'll need the URL Rewrite module installed. Add this rule to your root web.config file:
<configuration> <system.webServer> <rewrite> <rules> <rule name="Print-Scan to Printing Redirect" stopProcessing="true"> <match url="^print-scan/(.*)$" /> <action type="Redirect" url="/printing/{R:1}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
{R:1}references the content captured by the(.*)in the match pattern, preserving the rest of your URL path.redirectType="Permanent"ensures it's a 301 redirect.
Quick Tip:
Before deploying a permanent 301 redirect, test with a 302 temporary redirect first (change R=301 to R=302 in Apache, permanent to redirect in Nginx, and Permanent to Temporary in IIS). Browsers cache 301s aggressively, so testing with 302 avoids caching issues while you verify everything works as expected.
内容的提问来源于stack exchange,提问作者JGeer

