15

I'd like to use mod_rewrite to make pretty URLs, but have a single version of the .htaccess file that can be used for any user on a server.

So far I have the standard pretty URL .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$     /index.php/$1 [L]

Ideally, I would like something similar to

RewriteRule ^(.*)$     %{URL of this file's directory}/index.php/$1 [L]

This documentation would lead me to believe that what I want is not necessary:

Note: Pattern matching in per-directory context Never forget that Pattern is applied to a complete URL in per-server configuration files. However, in per-directory configuration files, the per-directory prefix (which always is the same for a specific directory) is automatically removed for the pattern matching and automatically added after the substitution has been done. This feature is essential for many sorts of rewriting - without this, you would always have to match the parent directory which is not always possible.

I still get the wrong result, though, whether or not I put a leading / in front of the index.php on the RewriteRule.

This,

http://server/test/stream/stream

turns into

http://server/index.php/stream

not

http://server/test/index.php/stream

when the .htaccess file is in /test/.

Allan
  • 1,635
  • 4
  • 15
  • 19

2 Answers2

16

I was having a similar problem, but found that simply leaving off the root '/' resulted in my test web server (xampp on windows) serving a URL similar to:

http://localhost/C:/xampp/htdocs/sites/test/

Not perfect. My solution is to use a RewriteCond to extract the path from REQUEST_URI. Here's an example for removing the unwanted "index.php"s from the end of the URL:

RewriteCond %{REQUEST_URI} ^(.*)/index.php$
RewriteRule index.php %1/ [r=301,L]

Note: the percent sign in "%1/", rather than a dollar sign.

%1-%9 gets the patterns from the last matched RewriteCond, $1-$9 gets the patterns from the RewriteRule.

See: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond

Cheers :)

Li1t
  • 622
  • 6
  • 16
  • 1
    Has there been any better update to this since you last posted the answer? I just "feel" like there has to be one. I do like your solution, though, and it's working for me. – Art Geigel Apr 30 '20 at 17:45
4

Turns out that it does matter whether I put a leading / in front of index.php or not. By leaving it off, the script works correctly. I had been testing with the R flag which was using physical directories on the redirect.

Allan
  • 1,635
  • 4
  • 15
  • 19
  • 2
    Yes, **but** [by leaving it off you are relying on the value of rewritebase](https://stackoverflow.com/a/11443194/632951), which **may not** be your htaccess parent folder. In any case, leaving it off is a hackish solution not a real solution. – Pacerier Oct 04 '17 at 02:46