Laim McKenzie Laim McKenzie - 1 year ago 67
Apache Configuration Question

SEO Friendly URL's with .htaccess

Had a look around before posting this and couldn't find anything that matched with my specific problem.

On my website, I prefer to have my URL's without .php in them, so I have that set up in in my .htaccess file and it works perfectly. At the moment I have a page on my site called "Albums", that are the top albums of the year currently. However, I'd like to also do it for next year and so on. Now, I can do it as albums?date=2017, but that looks ugly. I'm wanting to do it as, as it looks a lot nicer and it's more SEO Friendly.

What I have in my HTACCESS is as follows:

RewriteEngine On

# Remove PHP from file names
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

# Redirect albums.php?date=2017 to albums/2017
RewriteCond %{THE_REQUEST} \s/albums\?date=([0-9]+)\s [NC]
RewriteRule ^ /albums/%1? [R=301,L]
RewriteRule ^albums/([0-9]+)$ /albums?date=$1 [L]

Options -Indexes

# Error Document Redirects
ErrorDocument 403
ErrorDocument 404

albums.php?date=2017 works without the the redirects, but when I put the redirects in, it sends you to /albums/2017, but doesn't show anything on the page. If I remove my "Remove PHP from file names" redirections, it does show the information on the page. So obviously I've worked out that the error is caused due to the "Remove PHP from file names" section of the file, I'm just not sure how to fix it.

I'm not hugely knowledgeable with .htaccess and the RewriteEngine, only know enough or very basic things, so apologies if this looks horrendous. I've had a look to try and make sure that I've not made a duplication question, but sorry if I have,

Answer Source

Figured it out.

# Redirect albums.php?date=2017 to albums/2017
RewriteRule ^albums/([^/]*)$ /albums?date=$1 [L]

# Remove PHP from file names
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]