'Understanding RewriteRule & HTACCESS
I'm building a blog with a prety easy page structure, consisting of articles.php
, article.php
and categories.php
and I'd like to tidy up the url path for each page, however I'm having trouble understanding how the mod works.
Currently my articles
page is the home page, done using DirectoryIndex
, but my url looks like:
http://testblog.local.co.uk/?cat=all¤tpage=3
Where I'd like this to be:
http://testblog.local.co.uk/all/3
My htaccess code so far looks like:
DirectoryIndex articles.php
RewriteEngine On
RewriteRule ^/?([a-zA-Z_]+)/([0-9]+)$ articles.php?cat=$1¤tpage=$2 [L]
This does nothing to the url and does not show the page correctly. I've looked through countless online "Beginner Guides" and still can't work it out. Can anyone help?
Solution 1:[1]
Use the %{THE_REQUEST}
variable:
RewriteEngine On
RewriteCond %{THE_REQUEST} ^GET\ /articles\.php\?cat=([^&]+)¤tpage=(\d+) [NC]
RewriteRule ^ /%1/%2? [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/(\d+)/?$ /articles.php?cat=$1¤tpage=$2 [L]
Solution 2:[2]
Your rule (last row) needed a slight error correction:
OLD: RewriteRule ^/?([a-zA-Z_]+)/([0-9]+)$ articles.php?cat=$1¤tpage=$2 [L]
NEW: RewriteRule ^([a-zA-Z_]+)/([0-9]+)$ articles.php?cat=$1¤tpage=$2 [L]
Note 1: RewriteRule does NOT require the leading slash "/" and is NEVER met if there is one! In contrast, the RewriteCond require the leading slash...
Note 2: Not sure why you had the "?" char in front of the pattern?! Remaining of your tests?
Rule tested in https://htaccess.madewithlove.com and worked.
The regular expression tested in https://regex101.com .
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hjpotter92 |
Solution 2 | Hristo |