Victor
Victor

Reputation: 14622

htaccess rewrite rule fails

.htaccess is like rocket-science for me (and I guess I am not the only one). I am trying to create some RewriteRules to prettify my URLs.

RewriteEngine On
Options +FollowSymLinks
RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301]

RewriteRule (.*)/$ $1.php [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301]

RewriteRule ^download/(.*)/$ /download.php?fid=$1 [L]
RewriteRule ^students/(.*)/ /students.php?show_profile=$1 [L]

The PHP redirection works well (I mean, the URLs like /students.php become /students/ automatically). Now, I am particularly intersted in these two lines:

RewriteRule ^download/(.*)/$ /download.php?fid=$1 [L]
RewriteRule ^students/(.*)/ /students.php?show_profile=$1 [L]

So, when I write:

http://localhost/students/123

it becomes:

http://localhost/C:/xampp/htdocs/students/123/

and I get a 403 error document.

I dives me crazy, because I would like that this URL: http://localhost/students/?show_profile=123#photos to be http://localhost/students/123/#photos (and so on for other URLs)

My questions

  1. Where am I wrong, and how should my .htaccess file look lile?
  2. Is there any well-written reference or book that would teach me how to use and write .htaccess?

Upvotes: 1

Views: 164

Answers (1)

anubhava
anubhava

Reputation: 786041

Rearrange your rules, use option MultiViews and fix some regex in URI patterns.

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php
RewriteRule (.*)\.php$ /$1/ [L,R=301,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .*[^/]$ $0/ [L,R=301,NE]

RewriteRule ^download/(.*)/$ download.php?fid=$1 [L,QSA]
RewriteRule ^students/(.*)/ students.php?show_profile=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f [NC]
RewriteRule ^(.+?)/?$ $1.php [L]

Reference: Apache mod_rewrite Introduction

Apache mod_rewrite Technical Details

Apache mod_rewrite In-Depth Details

Upvotes: 1

Related Questions