You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过.htaccess实现旧URL到新系统URL的重定向?

How to Redirect Old URL Format to New Format Using .htaccess

Absolutely, this is totally achievable with Apache's mod_rewrite in your .htaccess file! Let's walk through the solution step by step.

The Approach

Your old URL includes extra segments we don't need (category name, category ID, subcategory ID, page title), so we just need to capture the two critical pieces: the country ID (first numeric segment) and the page ID (the number before the underscore in the final segment). Then we'll map those to your new URL structure.

The Rewrite Rule

Add this to your .htaccess file (make sure it's placed at the root of your website):

# Enable mod_rewrite (skip if already enabled elsewhere)
RewriteEngine On

# Permanent redirect from old URL to new URL
RewriteRule ^([0-9]+)/[^/]+/[0-9]+/[0-9]+/([0-9]+)_.*\.html$ /$1/$2.html [R=301,L]

Let's Break Down the Rule

  • ^([0-9]+): Captures the first numeric segment (your country ID) and stores it as $1.
  • /[^/]+/: Matches the category name (like computers)—we use [^/]+ to match any characters except a slash, since we don't need this value.
  • [0-9]+/[0-9]+/: Skips over the category ID and subcategory ID segments (we don't need these either).
  • ([0-9]+)_.*\.html$: Captures the numeric page ID right before the underscore, stores it as $2. The _.* ignores everything after the underscore (the page title), and \.html$ matches the file extension.
  • [R=301,L]: R=301 sets a permanent redirect (critical for SEO, as it tells search engines to update their indexes), and L means "last rule"—so Apache stops processing further rules once this one matches.

Important Notes

  • Check mod_rewrite: Ensure your Apache server has the mod_rewrite module enabled. If you're on shared hosting, this is usually already on, but if not, reach out to your host to enable it.
  • Test first with temporary redirect: If you're unsure, replace R=301 with R=302 (temporary redirect) to test. Once you confirm it works correctly, switch back to 301 for permanent SEO benefits.
  • Order matters: If you have other rewrite rules in your .htaccess, place this redirect rule at the top so it takes priority over other rules.

内容的提问来源于stack exchange,提问作者Blake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:44:17