apache - 如何重写htaccess规则以重定向到css文件

标签 apache .htaccess mod-rewrite

目标是能够通过 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 文件。

我尝试阅读这篇文章:

最佳答案

您可以在站点根目录 .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]

关于apache - 如何重写htaccess规则以重定向到css文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69773943/

相关文章:

.htaccess url 使用 ssl 重定向重写

apache - .htaccess 基于SSL协议(protocol)的重定向

javascript - 无法通过 xmlhttprequest 加载本地 xml 文件

apache - 将 {query}.ts 重写为 ts.php?{query}

apache - 重写所有带有 .html 扩展名的 url(index.html 除外)

wordpress - 域重定向到 https 问题

python - 使用 mod-python 使 HTTP 身份验证成为可选

linux - Apache 无法启动

php - 如何从 url slim 框架设置 VirtualHost 中删除 index.php?

apache - 使用 htaccess 重定向到同一域