Reputation: 101
In my website I a trying to change my link from this:
example.com/news/foobar.php?id=21&artName=Hello-World
to look like this:
example.com/news/foobar/21/Hello-World
in my .htaccess file I have the following code:
<FilesMatch "^\.htaccess">
Order allow,deny
Deny from all
</FilesMatch>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^/?(.*)/(.*)$ ^news/foobar.php?id=$1&artName=$2 [NC,L,QSA]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*) $1.php [L]
My link to the article looks like this:
<a href="https://www.example.com/news/foobar/'.$row['id'].'/'.$row['linkAddress'].'" class="post-title">'.$row['aName'].'</a>
Where it collects the id and name from the variable, whenever I click on that article link my website loads but the php Get variables are missing so the page does not display the article information (meaning article id and name are missing so page does not collect the information). I have tried rewriting the code in my .htaccess but this is the only one I found that did not end in a 404 error when I click the article. I have been stuck for some time, please let me know what I can do to fix this, thank you.
Upvotes: 1
Views: 64
Reputation: 6148
ReWriteRule
The structure of a rewrite rule is typically:
ReWriteCond SOME_CONDITION
ReWriteRule REGEX_FOR_INPUT_STRING OUTPUT_STRING [FLAGS]
In your case we don't strictly need a condition, so we can skip to the re-write rule:
RewriteRule ^news/foobar/(\d+)/([\w-]+)/?$ news/foobar.php?id=$1&artName=$2 [NC,L,NE]
Explanation
// Matching Regex:
^news/foobar/(\d+)/([\w-]+)/?$
^ : Matches the start of the string
news/foobar/ : Matches the first two "directories" in the URL
(\d+) : Capture group 1 to get the id
/ : Matches a slash between id and artName
([\w-]+) : Capture group 2 to capture artName
/? : Matches an optional closing /
$ : Matches the end of the string
// Replacement:
news/foobar.php?id=$1&artName=$2
news/foobar.php? : Path to file and start of query string (?)
id=$1 : First query parameter ($1 is a call back to capture group 1)
& : & goes between parameters in the query string
artName=$2 : Second query parameter ($2 is a call back to capture group 2)
// Flags:
[NC,L,NE]
NC : Makes the match case insensitive
L : Stops the .htaccess from applying further rules
NE : Stops the rewrite escaping the & in the query string.
Without it & would become %26
Side Note
Remember that, now, when navigating to pages you are using the url like:
example.com/news/foobar/21/Hello-World
<a href="example.com/news/foobar/21/Hello-World">Click me!!</a>
and in PHP you're still using $_GET
:
echo $_GET["id"]; // 21
echo $_GET["artName"]; // Hello-World
Upvotes: 1