Pergunta

So I'm not the best at this, and just have recently been looking into .htaccess editing to make my URL's look attractive, but I was wondering how I would go about rewriting my .htaccess code so that it works as I'd like it, if necessary?

The issue I'm running into is I can't figure out how to write the code for the parts where I need the three slugs $1, $2, and $3 (id, category, and image). Currently, the code I have doesn't work correctly when my PHP is checking if &image= is null or not; it does however work for the ?id=1&category=1.

My site contains a layout like this:

?id=work --> ?id=work&category=1 --> ?id=work&category=1&image=1
?id=shop --> ?id=shop&category=1 --> ?id=shop&category=1&image=1
?id=play --> ?id=play&category=1 --> ?id=play&category=1&image=1
?id=about
?id=archive --> ?id=archive&image=1

Which I'm trying to get to show as this:

/work --> /work/1 --> /work/1/1
/shop --> /shop/1 --> /shop/1/1
/play --> /play/1 --> /play/1/1
/about
/archive --> /archive/1

Here is my .htaccess:

Options +FollowSymLinks -MultiViews

RewriteEngine on
RewriteBase /

RewriteRule ^(.*)/(.*)$ index.php?id=$1&category=$2 [L,QSA]
RewriteRule ^work/(.*)/(.*)$ index.php?id=work&category=$2&image=$3 [L,QSA]
RewriteRule ^about$ index.php?id=about [L,QSA]
RewriteRule ^archive$ index.php?id=archive [L,QSA]
RewriteRule ^404$ index.php?id=404 [L,QSA]

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

ErrorDocument 404 http://example.com/404

I am sure there is a better way to write this; I know this is super wonky - but it is working with all BUT the &image= slug at the moment. A few other issues I've ran into has been folders and files being rewritten, in which I've used this code to fix:

# Allow any files or directories that exist to be displayed directly
RewriteCond ${REQUEST_URI} ^.+$
RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g|png|js|css|swf|php|ico|txt|pdf|xml)$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

Oh, and I haven't included the ?id=archive&image= part either - I just haven't been able to figure that out.

One last bit, but I've used this code and had it working to some extent - but ran into looping issues:

RewriteRule ^(.*)/(.*)/(.*)$ index.php?id=$1&category=$2&image=$3 [L,QSA]
Foi útil?

Solução

It seems you only need one rule if you make the second and third group optional:

RewriteRule ^([\w\d]+)(?:/(\d+)(?:/(\d+))?)?$ index.php?id=$1&category=$2&image=$3 [L,QSA]

Please note that:

  • I have used \w (word characters) and \d (digits) to restrict what is rewritten. This seems to be all you need and it will also avoid rewriting existing files (you could also add conditions for that);
  • I have used two non-capturing groups (?:...) to not mess-up the numbers of the variables.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top