SiteAppDev
SiteAppDev

Reputation: 141

htaccess - remove .jpg from the end of the url, then process all rewriting rules

I'm trying to create some URL rewrite rules that will get this URL:

https://example.com/abc/123.jpg

And rewrite to the following url:

https://example.com/?p=abc&u=123

So it will:

  1. Ignore ".jpg"
  2. Set the value after first "/" as p param
  3. Set the value after second "/" as u param

For #2 and #3 I have this (and it's working great):

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ ?p=$1 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/$ ?p=$1 [QSA]

RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ ?p=$1&u=$2 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ ?p=$1&u=$2 [QSA]

However, when I have ".jpg" at the end of the url I get apache error "Not Found".

Anyone knows what rule I need to add to .htaccess to ignore the ".jpg" in this case?

Thanks!

Upvotes: 1

Views: 171

Answers (2)

anubhava
anubhava

Reputation: 785731

You will have to make last .jpg or .jpeg optional in the end. You may use these 2 rules:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)(?:\.jpe?g|/)?$ ?p=$1 [L,NC,QSA]

RewriteCond %{REQUEST_FILENAME} !-d    
RewriteRule ^([\w-]+)/([\w-]+)(?:\.jpe?g|/)?$ ?p=$1&u=$2 [L,NC,QSA]

Note that \w is equivalent of [a-zA-Z0-9_].

Upvotes: 1

R. Martin
R. Martin

Reputation: 411

you can add .jpg on each rule to match only .jpg ending urls

RewriteRule ^([a-zA-Z0-9_-]+)\.jpg$ ?p=$1 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)\.jpg/$ ?p=$1 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\.jpg$ "?p=$1&u=$2" [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)\.jpg/$ ?p=$1&u=$2 [QSA]

Upvotes: 0

Related Questions