I’m having some trouble with my mod_rewrite fighting with my PHP code and not giving me the outcome I’d like.
Here is my original mod_rewrite, whose purpose was to take a “Pretty Article URL” and transform it into something PHP can handle…
RewriteRule articles/([a-zA-Z0-9_-]+)$ articles/article.php?slug=$1
This has been working fine, but when I re-wrote my PHP to be more security conscious, some of my PHP isn’t firing, because the mod_rewrite steps in.
Here is an outline of my “article.php” code…
<?php
// Attempt to Retrieve Article.
if (isset($_GET['slug']) && $_GET['slug']) {
// Slug found in URL.
// Check Slug Format.
if (preg_match('~(?x) # Comments Mode
^ # Beginning of String Anchor
(?=.{2,100}$) # Ensure Length is 2-100 Characters
[a-z0-9_-]* # Match only certain Characters
$ # End of String Anchor
~i', $_GET['slug'])){
// Valid Slug Format.
// Find Article Record.
// Check # of Records Returned.
if (mysqli_stmt_num_rows($stmt1)==1){
// Article was Found.
}else{
// Article Not Found.
// Display Error Page.
}//End of FIND ARTICLE RECORD
}else{
// Invalid Slug Format.
// Display Error Page.
}//End of CHECK SLUG FORMAT
}else{
// Slug Not found in URL.
// This will never fire!!
// Apache catches missing slug and re-routes to "articles/index.php"
}//End of ATTEMPT TO RETRIEVE ARTICLE
?>
Here is what specifically is happening…
I am okay with Apache taking over in the Level-1 IF statement if there No Slug.
However, for the Level-2 IF statement, I want my PHP code’s Regex to work and my PHP Error Page to fire of someone sent over something like this…
http://local.debbie/articles/SOME_BOGUS_ARTICLE_@@@@@@@@@
I tried changing my .htaccess file to this…
RewriteRule articles/(.+)$ articles/article.php?slug=$1
##RewriteRule articles/([a-zA-Z0-9_-]+)$ articles/article.php?slug=$1
But that doesn’t work, because if the user clicks “Add a Comment”, I take them to…
http://local.debbie/articles/add_comment.php
And the wildcard above tries to do this…
http://local.debbie/articles/article.php?slug=add_comment.php
…which obviously fails.
Then someone suggested I try this…
RewriteCond %{index.php} !-f
RewriteCond %{add_comment.php} !-f
RewriteRule articles/(.+)$ articles/article.php?slug=$1
##RewriteRule articles/([a-zA-Z0-9_-]+)$ articles/article.php?slug=$1
But that isn’t working either?!
I hope you can follow me here?!
Re-stated…
1.) I want to be able to have a Pretty Article URL like this…
http://local.debbie/articles/when-to-hire-a-consultant
2.) But I want my PHP to be able to scrutinize the “slug” for security purposes
3.) I want a pretty Error Page if the URL’s Format is Invalid
4.) I want a pretty Error Page if the Article is Not Found
5.) Whatever I do, needs to also work with a URL like these…
http://local.debbie/articles/add_comment.php
OR
http://local.debbie/articles/add_comment.php?article=52301
AND
http://local.debbie/articles/index.php
Thanks,
Debbie