简体   繁体   中英

htaccess: relative paths not working properly

First, what I am trying to achieve: I am testing under the base http://example.com/subdir and this is where all subfolders , index.php and .htaccess are.

I have 3 groups of rules as shown in the .htaccess (extra rules removed):

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on

# Convert   item/edit/xx -> index.php?p=edit&id=xx
# Convert   item/remove/xx -> index.php?p=remove&id=xx
#RewriteCond %{REQUEST_URI} ^/item [NC]
#RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC]
RewriteRule ^item/([a-z]+)/([0-9]+)$    index.php?p=$1&id=$2 [NC,L]

# Convert category/yyyy -> customer/pagination.php?category=yyyy

#RewriteCond %{QUERY_STRING} category=([a-zA-Z\s]+)$
RewriteRule ^customer/category/([a-zA-Z\s]+)$     customer/pagination.php?category=$1  [NC,L]


# Convert action/about   -> index.php?p=about
# Convert action/terms   -> index.php?p=terms


#RewriteCond %{QUERY_STRING} p=([a-z]+)$
RewriteRule ^action/([a-z]+)$     index.php?p=$1  [NC,L]

</IfModule>

The first problem I faced was the RewriteCond not working (giving Path not found), so it is commented out for the moment. RewriteRule works fine with absolute path (eg RewriteRule ^action/([az]+)$ http://example.com/subdir/index.php?p= $1 [NC,L]), however this causes the browser to display the real URL therefore I'm trying to make it work with relative paths. My issue is that after a first redirect the first part of the link on the left is added to the path, ie http://example.com/subdir becomes http://example.com/subdir/action after clicking action/about link. Defining RewriteBase or prepending slashes to the URLs only makes things worse. I will be grateful to an eagle-eyed expert who can spot the root cause of my problem.

The first problem is that %{REQUEST_URI} always includes the full path. So, your condition could be changed to:

RewriteCond %{REQUEST_URI} ^/subdir/item [NC]

The second problem would actually not be solved using .htaccess. You just need to tell the browser what you want. So, you can use one of two methods.

  1. Use the <base> element (which will apply to all relative URIs on the page):

     <base href="/subdir" />
  2. Use a relative path to the URL shown in the browser:

     <a href="terms">Click here</a>

If you really wanted to solve the problem using .htaccess, the only real way to do so would be to remove the duplicated directory after it has been requested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM