【问题标题】:Use .htaccess to rewrite a sub directory to root but keep access to other sub directories使用 .htaccess 将子目录重写为 root 但保留对其他子目录的访问权限
【发布时间】:2015-08-13 14:16:12
【问题描述】:

我正在尝试从我的 URL 结构中重写一个子目录,但该目录结构中的其他 URL 也可以工作。我有这种情况:

// This should load the content of mysite.com/foo/15 but not redirect
mysite.com/foo/ 

// Subdirectories within /15 should also work
mysite.com/foo/bar // the actual location of this is mysite.com/foo/15/bar

// Other URLs within this directory structure should also work, such as
mysite.com/foo/12
mysite.com/foo/13
mysite.com/foo/14

// Lastly, we have redirects from 2012 -> 12, 2013 -> 13 such that
mysite.com/foo/2012 becomes mysite.com/foo/12
mysite.com/foo/2013 becomes mysite.com/foo/13
... and so on

这就是我所在的位置。我无法获得正确的 htaccess 规则组合来实现我想要的。

RewriteEngine On
RewriteBase /foo/

// This makes mysite.com/foo/ load the content of mysite.com/foo/15 without redirecting, but makes mysite.com/foo/14 404
RewriteRule ^((?!15/).*)$ 15/$1 [NC,L]

// This works pretty well, except the rules below don't redirect
RewriteRule ^$ 15/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ 15/$1

// Rewrite old years to the two digit form
RewriteRule ^2010/(.*)$ 10/$1 [R=301]
RewriteRule ^2011/(.*)$ 11/$1 [R=301]
RewriteRule ^2012/(.*)$ 12/$1 [R=301]
RewriteRule ^2013/(.*)$ 13/$1 [R=301]
RewriteRule ^2014/(.*)$ 14/$1 [R=301]
RewriteRule ^2015/(.*)$ 15/$1 [R=301]

我错过了什么?什么样的规则组合可以帮助我实现我想要的?

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:

    您的重定向规则可以使用正则表达式匹配组合成单个规则:

    RewriteEngine On
    RewriteBase /foo/
    
    // Rewrite old years to the two digit form
    RewriteRule ^20(1[0-5])/(.*)$ $1/$2 [R=301,L]
    
    RewriteRule ^$ 15/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^((?!15/).*)$ 15/$1 [L]
    

    【讨论】:

    • 效果很好,谢谢! RewriteRule ^20(1[0-5])/(.*)$ $1/$2 [R=301,L] 很聪明。
    【解决方案2】:

    尝试在所有规则中包含 L 标志,然后将所有重定向放在 htaccess 文件的顶部:

    RewriteEngine On
    RewriteBase /foo/
    
    // Rewrite old years to the two digit form
    RewriteRule ^2010/(.*)$ 10/$1 [R=301,L]
    RewriteRule ^2011/(.*)$ 11/$1 [R=301,L]
    RewriteRule ^2012/(.*)$ 12/$1 [R=301,L]
    RewriteRule ^2013/(.*)$ 13/$1 [R=301,L]
    RewriteRule ^2014/(.*)$ 14/$1 [R=301,L]
    RewriteRule ^2015/(.*)$ 15/$1 [R=301,L]
    
    // This makes mysite.com/foo/ load the content of mysite.com/foo/15 without redirecting, but makes mysite.com/foo/14 404
    RewriteRule ^((?!15/).*)$ 15/$1 [NC,L]
    
    // This works pretty well, except the rules below don't redirect
    RewriteRule ^$ 15/ [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ 15/$1 [L]
    

    【讨论】:

    • 访问 mysite.com/foo/14/ 时出现内部服务器错误
    猜你喜欢
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多