也许您应该澄清用户尝试访问真实 URL 时的预期行为:
www.example.com/public/file1/
如果 prevent 你的意思是禁止,你可以添加一个规则来回复 403
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !/public/
RewriteRule ^(.*)$ /public/$1 [L]
RewriteCond %{REQUEST_URI} /public/
RewriteRule ^(.*)$ / [R=403,L]
</IfModule>
更新:上面的解决方案不起作用!
我意识到我之前的解决方案总是抛出 403,所以它毫无价值。实际上,这有点棘手,因为重定向本身确实在 URL 中包含 /public/。
真正对我有用的解决方案是将 secret 查询字符串附加到重定向并检查包含 /public/ 的 URL 上的此值:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !/public/
RewriteRule ^(.*)$ /public/$1?token=SECRET_TOKEN [L]
RewriteCond %{REQUEST_URI} /public/
RewriteCond %{QUERY_STRING} !token=SECRET_TOKEN
RewriteRule ^(.*)$ / [R=403,NC,L]
</IfModule>
这样www.example.com/file1/ 会显示file1,但www.example.com/public/file1/ 会抛出403 Forbidden 错误响应。
关于此SECRET_TOKEN 的安全性的问题在这里讨论:How secure is to append a secret token as query string in a htaccess rewrite rule?
如果您的 URL 应该有自己的查询字符串,例如 www.example.com/file1/?param=value,请务必添加标志 QSA。
RewriteRule ^(.*)$ /public/$1?token=SECRET_TOKEN [QSA,L]