请求编写.htaccess 301重定向规则优化URL提升SEO友好度
301 Redirect for SEO-Friendly URL Rewrite (Apache .htaccess)
Hey there! Let's work through this 301 redirect to get those old, database-ID URLs pointing to your new SEO-friendly ones without tanking your SERP rankings. Here's a step-by-step solution using Apache's mod_rewrite in .htaccess:
Step 1: Understand the URL Patterns
First, let's confirm the patterns we're matching and rewriting:
- Old URL:
/shows/[base-name-with-underscores]_[version]_[db-id].htm(e.g.,/shows/my_personal_show_2.0_34565.htm) - New URL:
/shows/[base-name-with-hyphens]-[version]-[base-name-with-hyphens].htm(e.g.,/shows/my-personal-show-2.0-my-personal-show.htm)
Step 2: .htaccess Rewrite Rules
Add these rules to your site's root .htaccess file (make sure mod_rewrite is enabled on your Apache server):
# Enable mod_rewrite RewriteEngine On # Loop to replace all underscores in the base name with hyphens # Handles base names with multiple underscores (like "my_personal_show") RewriteRule ^shows/([^_]*)_([^_]+)_([^_]+)_(\d+)\.htm$ /shows/$1-$2_$3_$4.htm [N] # Final rewrite: map cleaned old URL to new SEO structure with 301 permanent redirect RewriteRule ^shows/([^_]+)_([^_]+)_(\d+)\.htm$ /shows/$1-$2-$1.htm [R=301,L]
Step 3: Breakdown of the Rules
- First Rule: This loops through the base name (e.g.,
my_personal_show) and replaces each underscore with a hyphen one by one until no underscores remain. The[N]flag tells Apache to restart the rewrite process with the modified URL, ensuring every underscore gets converted. - Second Rule: Once the base name is free of underscores, this rule matches the cleaned old URL (e.g.,
/shows/my-personal-show_2.0_34565.htm) and redirects it to the new structure. The[R=301]flag sets a permanent redirect (critical for preserving SEO authority), and[L]stops further rewrite processing for that request.
Key SEO & Implementation Notes
- Test First: Always verify redirects before deploying to production. Use
curl -I [old-url]to check for a301 Moved Permanentlystatus code pointing to the correct new URL. - Avoid Loops: Your new URLs use hyphens instead of underscores for the base name, so they won't trigger the old URL pattern—no redirect loops to worry about.
- Google Index Update: It may take Google a few weeks to update its index with the new URLs, but 301 redirects will pass most of your existing SEO ranking to the new pages.
- 404 Prevention: Make sure the new URLs are fully functional and serve the correct content before enabling the redirects.
内容的提问来源于stack exchange,提问作者Endri Bedini
相关产品推荐
相关产品推荐

