natanel97 natanel97 - 6 months ago 15
PHP Question

.htaccess Redirects wrong and looping

I'm trying to refer urls (e.g. from

page.php?page_id=1
to
page/1
or
page/pagename
or just
pagename
), using this code:

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteBase /subdirectory/

# If user tries to access "subdirectory/page" without "get" then
RewriteRule ^page/ page.php [L]

# If user tries to access "subdirectory/page/1" or "subdirectory/pagename" then
RewriteRule ^page/1 page.php?page_id=1 [L]
RewriteRule ^page/pagename page.php?page_id=1 [L]

# If user tries to access "subdirectory/pagename" only then
RewriteRule ^pagename page.php?page_id=1 [L]


If I turn it off (
RewriteEngine Off
or even deleting the entire .htaccess file) and if I turn it on, it does the wrong thing - It redirect itself to parent directory (localhost
www
folder), e.g. from
subdirectory/page/etc.
to
page/etc.
. If it finally works, after I try again and again (and again and again...) to change it non-stop in order to make it work, It causes an infinite loop when it has a trailing slash (such as
page/1
or
page/somepage
) or it just not display the page properly (because the browser treats it like it was a real path / folder and not a slug)

I know I probably did something wrong (i'm new to .htaccess) but I don't know what... any thoughts?

Thank you very much.

Update: the .htaccess file is inside the "subdirectory" folder. There is another .htaccess file in the www folder (main folder of localhost that also include the "subfolder") which contains this:

# RewriteEngine On
#
# ErrorDocument 404 /err.php?id=404
# ErrorDocument 403 /err.php?id=403
# ErrorDocument 500 /err.php?id=500


It's commented just because that this is the only way to disable it - I tried the "rewriteengine off", had no success

Answer

You can use these rules :

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /subdirectory/  
#if an existent file or dir is requested,serve it immideatly 
RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
#####
    # If user tries to access "page" without "get" then
RewriteRule ^page/ page.php [L]

# If user tries to access "page/1" or "pagename" then
RewriteRule ^page/1 page.php?page_id=1 [L]
RewriteRule ^page/pagename page.php?page_id=1 [L]

# If user tries to access "pagename" only then
RewriteRule ^pagename page.php?page_id=1 [L]
Comments