简体   繁体   中英

mod_rewrite RewriteRule and html links

I'm creating a new website and it has some php in it. The site basically would work like this, i have /index.php?page=category_page. The the category would be the category and the page would be the sort-of sub category / actual page. The rewritten rule would look like this: /category/page.

I've got this:

RewriteEngine On
RewriteRule ^category/([^/]*)$ index.php?page=$1 [L]

But i dont know how to separate the category and the page, any help? The second thing is, in my index.php (for instance) i have some css from an external file:

<link rel="stylesheet" type="text/css" href="style/style.css"/>

This doesn't work with the rewrite rule, because it tries to load /category/page/style/style.css which doesn't exist / doesn't rewrite. How do i make it work? I know a simple fix would be to put /style/style.css and that would load from the root of the website, but i'm currently running the website from a sub directory eg example.com/new/index.php so that isn't an option. Any help with this?

Problem 1:

You could define multiple parameters in your regex, eg category & page (see below).

With such a broad rewrite rule, you would want to add a condition not to rewrite for stylesheets, images, and other assets, though.

I also modified your pattern to only match letters, digits, hyphens, and underscores, which would prevent the use of non-standard characters in your category or page names.

RewriteEngine On
RewriteCond %{REQUEST_URI} !\.(js|css|png|gif|jpg)$ [NC]
RewriteRule ^([\w\d\-]+)/([\w\d\-]+)/?$ index.php?category=$1&page=$2 [L]

Problem 2:

You're using a relative url in your href, which is appending the stylesheet's location to the current location defined in your browser (/category/page/).

Even though the server-side is rewriting that URL, the browser is unaware of the rewrite.

If you use an absolute URL instead, your browser will define the URL relative to the BASE url (/).

Try this:

<link rel="stylesheet" type="text/css" href="/style/style.css"/>

Use this RewriteRule

RewriteEngine On
RewriteRule ^(.+)/(.+)/$ index.php?page=$1_$2 [L]

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