【问题标题】:Organizing code: redirect without changing url using .htaccess组织代码:使用 .htaccess 重定向而不更改 url
【发布时间】:2016-04-11 20:09:01
【问题描述】:

我有一个网站,其中有一个主页(业务内容)和一个文件夹,其中包含位于不同文件夹中的单独项目:

  • index.html
  • /js
  • /css
  • /图片
  • /博客
  • /项目

我想将所有主页资产移动到一个名为“站点”的文件夹中。我想要的是如下结构:

  • /网站
    • index.html
    • /js
    • /css
    • /图片
  • /博客
  • /项目

当我的用户访问 www.example.com 时,浏览器应在不更改 url 的情况下加载 /site 资源,而当他们访问 www.example.com/blog 时,浏览器应加载 /blog 资源(如预期的那样)。

我正在尝试在我的根文件夹中使用 .htaccess 文档,并将其放在上面:

RewriteEngine on
RewriteRule /(.*) /site [R]

但它不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: apache .htaccess


    【解决方案1】:

    [R] 标志会导致向浏览器发出 HTTP 重定向。

    试试这个:

    RewriteEngine On
    RewriteBase /
    # Ensure you do not running in redirection loop
    RewriteCond %{REQUEST_URI} !^/site/
    # Proceed if target is not a directory (handle accessing /blog, etc)
    RewriteCond %{REQUEST_FILENAME} !-d
    # Proceed if target is not a file
    RewriteCond %{REQUEST_FILENAME} !-f
    # Redirect all incoming requests to site/
    RewriteRule ^(.*)$ /site/$1 [L]
    # Redirect domain itself to the main site file (index.html, index.php, etc)
    RewriteCond %{HTTP_HOST} ^(www.)?example.com$
    RewriteRule ^(/)?$ index.html [L]
    

    请注意,您应该:

    • 将site 的所有实例替换为您的子目录
    • 将 example.com 替换为您的 TLD 域。

    【讨论】:

    • 谢谢。我尝试了您的解决方案,但是当我进入 www.example.com 时,没有加载任何内容(仅文件树)。我是否需要为每个资产定义一个规则才能正确加载?例如,我在 /. 上输入时的 index.html
    • 我更新了答案。我添加了 cmets 以便更好地理解。祝你好运!
    • 像魅力一样工作。谢谢vitozev!
    猜你喜欢
    • 2014-05-25
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    相关资源
    最近更新 更多