【问题标题】:Rewrite root to subfolder (.htaccess) except some directories将根目录重写为子文件夹(.htaccess),但某些目录除外
【发布时间】:2018-08-09 16:19:31
【问题描述】:

我有以下文件夹结构:

  • app/(包含 index.php、js/、public/)
  • v1/
  • .htaccess

对 v1 的请求应该照常工作 所有其他请求都应该转到 /app 而不更改 url

www.xxx.com/           (displays: app/index.php)
www.xxx.com/v1         (displays: v1/index.php)
www.xxx.com/js/xxx.js  (displays: app/js/xxx.js)

这可能吗?

基本上是静态文件夹: v1、app/js(无应用)、app/public(无应用)

所有其他请求都转到 app/index.php 而不更改 url。

【问题讨论】:

  • 有趣的问题!
  • 不是那么有趣,这基本上是大多数框架所做的。

标签: php apache .htaccess routing


【解决方案1】:

要将请求从/root 重写为/subfoldwr,您可以在/.htaccess 中使用以下规则

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /app/index.php  [L]

这会将除了现有文件/目录之外的所有内容从您的/root 素材重写为/app/index.php

【讨论】:

    【解决方案2】:

    您可以在站点根目录 .htaccess 中使用此规则:

    RewriteEngine On
    
    # landing page
    RewriteRule ^/?$ app/index.php [L]
    
    # if v1/file exists then use it
    RewriteCond %{DOCUMENT_ROOT}/v1/$1 -f
    RewriteRule .+ v1/$0 [L]
    
    # if app/public/file exists then use it
    RewriteCond %{DOCUMENT_ROOT}/app/public/$1 -f
    RewriteRule .+ app/public/$0 [L]
    
    # if app/js/file exists then use it
    RewriteCond %{DOCUMENT_ROOT}/app/js/$1 -f
    RewriteRule .+ app/js/$0 [L]
    
    # if not a file, not a dir and not starting with v1    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule !^v1/ app/index.php [L,NC]
    

    【讨论】:

    • 试过这个,去 www.xxx.com 时找不到页面。不确定我的域名托管服务商是否有一些奇怪的 apache 设置可能需要被覆盖。
    • 是的,我发现的很多应该有效的选项都没有。我有 one.com 作为域名托管服务商,也许他们的一些 apache 设置需要被覆盖?
    • .htaccess 已启用,我之前在这里修复了一些东西。然而,我得到的关于这个问题的提示似乎都没有奏效。
    • 我刚刚开始工作,将用我的发现更新帖子。
    猜你喜欢
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2012-10-23
    • 2017-01-29
    • 2021-09-03
    相关资源
    最近更新 更多