如何在PHP中返回静态文件?

问题描述:

我使用.htaccess文件将所有请求重定向到相同的index.php.从那里,我根据传入请求的URL决定要做什么.

I use a .htaccess file to redirect all requests to the same index.php. From there, I decide what to do depending on URL of the incoming request.

现在,我将请求URL映射到相对于source文件夹的目录结构,以便example.com/user/create映射到source/user/create/index.php.位于此处的文件可以根据需要处理请求,并生成HTML输出.

For now, I map the request URL to directory structure relative to a source folder, so that example.com/user/create maps to source/user/create/index.php. The file located there can handle the request as needed, and generate HTML output.

但这不适用于静态资产,浏览器可能会请求.因此,我的想法是找出请求URL是否以文件扩展名结尾并将其映射到相对于assets文件夹的目录结构,以便example.com/css/default.css将映射到assets/css/default.css.但是我不知道如何用静态文件而不是PHP的HTML代码来响应.

But that doesn't work for static assets, the browser may request. So my idea is to find out whether a request URL ends with a file extension and map that to a directory structure relative to a assets folder, so that example.com/css/default.css would map to assets/css/default.css. But I don't know how to respond with a static file instead of HTML code from PHP.

通常,这可以使用其他.htaccess规则来完成,但我想在代码中动态更改资产文件夹.

Normally, this might be done using an additional .htaccess rule, but I'd like to change the assets folder dynamically in code.

如何使用PHP将服务器硬盘上提供的静态文件发送到浏览器客户端?

How can I send a static file, given on the server's hard drive, to the browser client in PHP?

在紧急情况下

#Expections
RewriteCond %{REQUEST_URI} ^/assets.*$
RewriteRule ^(.*)$ - [L,NC]

#You redirect to index
...

在文件路径的开头加上/

put a / at the beginning of the file path

/assets/path/to/file