【问题标题】:how to rewrite the htaccess rules to redirect to css files如何重写 htaccess 规则以重定向到 css 文件
【发布时间】:2021-10-30 05:23:52
【问题描述】:

目标是能够在index.php文件中以/css/index.css这种方式访问​​CSS文件,但CSS文件的真正路径是./resources/styles/index.css

如果用户打开网站,例如https://stackoverflow.com/

它必须将用户重定向到 public/index.php 文件(入口点),但同时所有 CSS 文件(实际上都位于 resources/styles/ 目录下,并且必须可以使用此 url 访问它们: https://stackoverflow.com/css/index.css,并相应地应用于 HTML 页面。

我目前的项目结构:

public/
├─ .htaccess
├─ index.php
resources/
├─ styles/
│  ├─ index.css
│  ├─ main.css
.htaccess

我的./public/index.php 文件(必须是入口点):

<!doctype html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/css/index.css">
    {{-- but the actual path to index.css is "./resources/styles/index.css"--}}
</head>
<body>
...
</body>
</html>

我已经尝试过这个.htaccess 配置(从根目录),但它返回给我Not Found - 404 页面:

RewriteEngine on

RewriteBase /
RewriteCond %{REQUEST_URI} /resources/styles/.*
RewriteRule ^resources/styles/(.*)$ /css/$1 [QSA,L]
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]

我在这里想念什么?如果可能的话,请用一些额外的细节来描述它。

我的./public/.htaccess 配置:

RewriteEngine On
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

另外,对这些 ([js, fonts, images]) 类型执行相同操作的最佳方法是什么?

我知道这可以在 apache 配置中以这种方式完成:

...
Alias /css "/var/www/html/resources/styles"
<Directory /var/www/html/resources/styles>
                Options FollowSymLinks
                AllowOverride None
                Require all granted
</Directory>
...

如果 apache 配置中缺少某些内容,请纠正我。

但是,目前,我需要能够使用.htaccess 文件。

我已尝试阅读此帖子:

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    您可以在站点根目录 .htaccess 中包含这些规则:

    RewriteEngine On
    
    # rewrite css files to their actual path
    RewriteRule ^css/(.+\.css)$ resources/styles/$1 [L,NC]
    
    # rewrite js files to their actual path
    RewriteRule ^js/(.+\.js)$ resources/js/$1 [L,NC]
    
    # write root to public/
    RewriteRule ^$ public/ [L]
    
    RewriteRule ^(?!resources/).* public/$0 [L,NC]
    

    【讨论】:

    • 对不起,@anubhava,我没有正确提到 PHP 的 entry-point 必须是 public/index.php 文件。默认情况下(在我的情况下)Apache 服务器指向根目录(因此根目录中的主要.htaccess)用于重定向到public/index.php。您能否在 cmets 中发布执行此操作所需的更改或编辑您的答案?如果我用RewriteRule ^$ public/ [L] RewriteRule ^ public/index.php [L] 替换最后两行(就像以前一样),并尝试打开我的/css/index.css 文件,它会将我重定向到public/index.php 而不是css 文件。
    • 好的,检查我更新的答案以在站点根目录 .htaccess 中使用
    • 是的,但是如果我有RewriteRule ^resources/ public/index.php [L,NC],这仍然不起作用(resources/styles/index.css 将我重定向到主页public/index.php。如果这样设置:RewriteRule ^public/index.php [L,NC],它可以工作,但出现 favicon 错误
    • 你的favicon.ico在哪里?
    • 对不起,我有一个错字。最后一行应该是RewriteRule !^resources/ public/index.php [L,NC](请检查更新的答案)
    猜你喜欢
    • 2015-12-25
    • 2011-03-01
    • 2013-01-21
    • 2020-11-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多