简体   繁体   中英

Using PHP Files As CSS File With CSS Extension

I've been doing some reading on using PHP files as CSS files. I understand how to do that, but I want to take it a step further if possible.

Let's say I have a file called main-styles.php which contains my websites main style sheet.

If I want to link to this file I would simply use <link rel="stylesheet href="http://example.com/css/main-styles.php"> .

Simple enough, but what I am wanting to do is instead of having a .php extension I would like to have a .css extension instead but the file still be .php .

Would this be possible through mod_rewrite or something?

I was thinking something like RewriteRule ^(.+)\\main-styles.php$ $1main-styles.css .

Would that be sufficient?

If I'm not mistaken that rule would not work. I'm no expert in rewrite rules so bear with me.

EDIT

I've tried the following in my .htaccess file:

RewriteEngine on RewriteBase / RewriteCond %{REQUEST_URI} !\\.(?:css|png|jpe?g|gif)$ [NC,OR] RewriteRule universal.css universal.php [L]

Solved see my own answer.

You can use the H or T flag of apach mode rewrite to force all files with php extension to be parsed by The css handler :

try the following in htaccess :

RewriteEngine On
RewriteRule ^main-style\.php$ - [H=text/css]

or

RewriteEngine On
RewriteRule ^main-style\.php$ - [T=text/css]

The rules above will change the mime type of main-style.php.

So I figured it out finally. Turns out I had to list my directory.

Using the following in my .htaccess :

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !\.(?:css|png|jpe?g|gif)$ [NC,OR]
RewriteRule css/universal.css css/universal.php [L]

I was able to keep my stylesheet a php file, but load it using a css extension.

<link rel="stylesheet" href="http://example.com/css/universal.css">

Is handled as if it's

<link rel="stylesheet" href="http://example.com/css/universal.php">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM