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

如何通过.htaccess实现example.com/abc到https://www.example.com/abc的重定向?

Fixing Non-WWW/HTTP to WWW/HTTPS Redirection for Specific Paths

Hey there! Let's get this redirection working properly for you. The core issue with your current .htaccess setup is the order of your rewrite rules—Apache processes rules from top to bottom, and your internal routing rule was running before the domain/HTTPS redirects, which could cause unexpected behavior (like the redirect not triggering as expected for paths like /abc).

Here's the corrected .htaccess code:

RewriteEngine On

# 1. Redirect all non-WWW OR HTTP requests to HTTPS + WWW
# This automatically handles example.com/abc → https://www.example.com/abc
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

# 2. Handle internal application routing (your original rule, now after redirects)
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

What changed and why?

  • Rule order matters: We moved the domain/HTTPS redirect to the top. This ensures every incoming request (including /abc) first gets redirected to the correct https://www.example.com address before any internal application routing happens.
  • Combined redirect rule: We merged the non-WWW and HTTP checks into one rule using the [OR] flag. This way, any request that's either missing www. or using HTTP gets redirected to the fully qualified HTTPS + WWW URL, preserving the full path (like /abc).
  • R=301 flag: This is a permanent redirect, which is best for SEO and tells browsers to cache the redirect. If you're testing, you can use R=302 (temporary) first to avoid caching issues, then switch to 301 once everything works.

Quick Notes:

  • Replace example.com with your actual domain name.
  • Make sure your server has mod_rewrite enabled (most shared hosts have this on by default).
  • Clear your browser cache before testing, since old redirects might be cached.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:35:04