.htaccess用于路由单页应用程序

时间:2016-03-03 11:30:54

标签: apache .htaccess mod-rewrite routing

我正在开发一个单页面应用程序,我将各种模块加载作为路径推送到URL。我们有内置的处理程序来在内部更改参数的路径。

但要使其成为可收藏的,我们必须使用.htaccess来管理路径。

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^applications/sample([/]+[a-z]+)+$ applications/sample/index.html [L]
</IfModule>

现在这已经到了第一级......

applications/sample/module正在加载....但是

applications/sample/module/submodule无效...

RewriteRule我哪里错了?我正在寻找以下规则......

<rule>
  <note>Rewrite sample/module1, sample/module2, ... sample/moduleX to /sample/index.html and sub-modules as well</note>
  <from>/sample/(home|book|table|...|module)(.*)</from>
  <to>/sample/index.html</to>
</rule>

1 个答案:

答案 0 :(得分:1)

  

对于其工作sample/module的第一条路径...但是对于sample/module/sub-module它不起作用... css js文件正在抛出404

如果您在客户端HTML中使用外部资源(JS,CSS和图像)的相对URL,则会发生这种情况。由于第二个URL实际上位于(虚拟)&#34;子目录&#34;中,因此任何相对客户端URL都相对于&#34;子目录&#34;而不是父目录,因为它与第一个URL相关URL。

有关详细信息,请参阅我在Pro网站管理员上的回答:
.htaccess rewrite url leads to missing css

如果相反,链接的外部资源(即JS和CSS文件)正在被重写,那么您可以通过添加一些条件/异常来防止这种情况。要在访问静态资源(文件系统上的物理文件)时排除重写:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^applications/sample(/[a-z]+)+$ applications/sample/index.html [L]

我还调整了RewriteRule正则表达式,以防止接受多个斜杠。 (我假设你不需要捕获多个斜杠?)