asto
asto

Reputation: 197

Htaccess Regex won't match

I'm in desperate need of a quick tip.

Trying to use htaccess to change this not so lovely url

http://localhost/test/index.php?page=Article&articleID=61

to

http://localhost/test/article/2015-09-21-this-is-the-headline

From what I've gathered I need to send the last part to a php script which can then get the matching id from the database. Knowing that I should be able to send the user to the original url up top.

RewriteRule ^(.*)\/article\/(.*)$ redirect/article.php [L]
# RewriteRule ^(.*)$ index.php

As of right now I'm not passing the information to the script yet. redirect/article.php only contains a print statement to let me know once I get that far.

However, despite my brain and every regex debugger saying otherwise, it won't match the url provided in the second code box. All I'm getting is the good old 404. If I activate the second rule it is applied to my url, telling me that the first one is simply being skipped.

What am I missing?


.htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # rename individual pages
    RewriteRule ^(.*)\/article\/(.*)$ redirect/article.php [L]
    # RewriteRule ^(.*)$ index.php

    # resize images    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.)*\/([0-9]+)\-(([0-9]|[a-z])+)\.(prev)$ filePreview.php?id=$2&size=$3 [L]

    php_value upload_max_filesize 20M
    php_value post_max_size 21M
</IfModule>

Upvotes: 1

Views: 189

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

The location of a .htaccess file informs how you must list paths for mod_rewrite. Inside .htaccess, paths for RewriteRule are not received with a leading /. Since yours was residing in /test, the (.*) at the start of your rule wasn't matching anything and harmless. Since that was followed by /, the article/ path was expecting a / it would never receive. The simplest fix is to change this rule to match article at the start via:

RewriteRule ^article/(.*) redirect/article.php [L]

Assuming you'll use that as a lookup in the PHP script, add a parameter to use the $1 captured pattern like:

RewriteRule ^article/(.*) redirect/article.php?article=$1 [L]

Upvotes: 1

Related Questions