So I'm no .htaccess expert, by no means, but I have managed to put this code together for a webiste I'm making:
Options -Indexes +Includes
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]
RewriteRule ^\.htaccess$ - [F]
RewriteRule ^$ /%{ENV:BASE}/index.php?id=home
RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ $1 [R=301,L]
RewriteRule ^([a-zA-Z0-9]*)$ /%{ENV:BASE}/index.php?id=$1 [QSA,L]
</IfModule>
It basically changes www.example.com/some/dir/index.php?id=home
to www.example.com/some/dir/home
while the first few rules are creating some kind of relative path value so I don't have to change the RewriteBase everytime I change the base folder (this is important for this project!).
It works perfectly fine, but now I have encountered a problem where there have to be spaces in the URL like www.example.com/some dir/sub folder/home
and this messes everything up.
If you click a link on the page (e.g. "href="home"
") it redirects to www.example.com/home
instead of www.example.com/some dir/sub folder/home
with a 404 error, obviously (even though it works if there are no spaces!). I found out if right click > "copy link to clipboard" it becomes the encoded version www.example.com/some%20dir/sub%20folder/home
even if it shows the decoded version in the address bar. BUT if you manually type the decoded version www.example.com/some dir/sub folder/home
it still works fine.
There seems to be a problem with spaces and encoding. How do I get my hyperlinks working properly?
-- EDIT --
Thanks to the tutorial posted by elcodedocle, I simply added backslash space: ^([a-zA-Z0-9/ ]*)$
to the regex in the last rule, even if it's not the best method. Then I noticed the [L]
flag in the second last rule. I removed it because this shouldn't be the last rule (don't know why it was there in the first place...) and now it works! Well, kind of...
Now, If there is a trailing slash at the end of the URL it sill doesn't work anymore. Probabply because of the removal of the [L]
flag in the rule but I don't know how to fix this...