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

.htaccess将子目录重写为根目录,解决直接访问子目录不跳转问题

Fixing the Missing Redirect for Direct /public/ Access

Alright, I see the issue here—your current rules work great for serving content from the public directory without showing it in the URL, but they don’t handle the case when someone directly navigates to https://example.com/public/ or any subpath under /public/. Let’s fix that by adding a redirect rule that catches those direct requests and sends users to the clean URL.

Here’s the updated .htaccess code that handles both the internal rewrite and the external redirect:

RewriteEngine On
Options +FollowSymLinks

# Redirect direct requests to /public/... to the root URL (without /public/)
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+public/([^\s]+)\s [NC]
RewriteRule ^ /%1 [R=301,L]

# Redirect direct request to /public/ (trailing slash) to root
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+public/\s [NC]
RewriteRule ^ / [R=301,L]

# Original internal rewrite rules to serve content from /public/
RewriteRule ^$ public/ [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ public/$1 [L]

Let’s break down what each part does:

  • The first two redirect rules: These use %{THE_REQUEST} (which captures the original request sent by the browser, not the rewritten one) to detect when someone is directly accessing /public/ or /public/.... We then redirect them to the equivalent URL without the /public/ prefix using a 301 permanent redirect (great for SEO consistency).
  • The original rewrite rules: These stay in place to internally route clean URLs (like https://example.com or https://example.com/faq.php) to the actual files in the public directory, keeping the URL clean for users.

Why your original rules didn’t handle this:

Your existing rules only handle the "forward" direction—taking clean URLs and serving content from public. They don’t address the reverse scenario where users type the public path directly into their browser. By checking %{THE_REQUEST}, we can distinguish between direct browser requests and internally rewritten requests, ensuring we only redirect when needed.

Note: If you’re still testing, you can use R=302 instead of R=301 to use a temporary redirect. Once you’re sure everything works as expected, switch back to R=301 for permanent redirects.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:44:56