3

So I'm trying to get a mod_rewrite rule to redirect requests to a php-script with an .htaccess file. The thing is, I want it to work regardless of where I put the project on a webserver (the .htaccess file and the php-script are always in the same folder).

The rewrite itself is very simple. If the script and the .htacess are in the directory /path/to/project and the user visits:

/path/to/project/somestring

it should be rewritten to:

/path/to/project/index.php?t=somestring

This should work for every subdirectory at any level in the webserver. So:

If the php-script and the .htaccess files are in the root:

/somestring2

should be rewritten to:

/index.php?t=somestring2

If the php-script and the .htaccess file are in /subdirectory:

/subdirectory/somestring3

should be rewritten to:

/subdirectory/index.php?t=somestring3

So the RewriteRule should perform the same rewrite action regardless of where the project lives within the server. The string that is to become a GET-parameter can consist of those characters: [a-zA-Z0-9]. If there are other GET-parameters in the requested URL, they should be appended as well (hence the QSA flag). This is what I've tried:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*/)([a-zA-Z0-9])/? $1index.php&t=$2 [L,QSA] 

However, this results in a 404 error. How can I alter it to do what I want?

MoritzLost
  • 2,611
  • 2
  • 18
  • 32

1 Answers1

2

Try :

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/)?([A-Za-z0-9]+)/?$ /$1index.php?t=$2 [NC,L,QSA]

Note that a leading slash in rewrite pattern is not required in the RewriteRule context.

Mike Rockétt
  • 8,947
  • 4
  • 45
  • 81
Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • Oh I forgot the modifier for the second group, now I feel stupid :/ Is the End of Line Anchor ($) at the end really a good idea? Won't this stop the Rule from working when another GET-parameter is present? Hm, I tried it, but it still gives an 404 error .. – MoritzLost Jan 19 '16 at 13:48
  • 1
    Ok I fixed a typo (still had & instead of ? after .php, now I feel more stupid than before), now the redirect triggers. However, it didn't redirect to the php-script, but to the XAMPP dashboard. So I removed the leading slash in the rewrite pattern and now it works. The first group includes the leading slash of the request_uri, so the rewrite pattern resulted in two leading slashes, which seems to be causing the problem. Maybe edit that out of your answer (or change the beginning to ^/([^/]+/)? that should also work). Thanks! – MoritzLost Jan 19 '16 at 14:12