问题原文
原帖链接 · andy · CC BY-SA 3.0
I am trying to remove the sub-folders from my site URL.
Below is the structure of my folders. I am not sure where to place my .htaccess file and what to have written in it:
- mysiteroot
- subdir1
- subdir2
- index.php
- page1.php
- page2.php
- page3.php
I have written the following:
RewriteEngine On
RewriteRule ^$ subdir1/subdir2/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ subdir1/$1
It seems to only work for the index with my .htaccess file placed in the mysiteroot folder.
How can I make the request for page1.php to show www.mysiteroot.com/page1 instead of www.mysiteroot.com/subdir1/subdir2/page1.php?
已采纳解答
原帖链接 · MrWhite · CC BY-SA 3.0
I had already written most of this before you posted your solution. Posting anyway as a more general solution that readers may find useful.
How can I make the request for
page1.phpto showwww.example.com/page1instead ofwww.example.com/subdir1/subdir2/page1.php?
You do this by physically changing the URLs in your application, not in .htaccess. Once the URLs have been changed in your application, the request is then for www.example.com/page1, the visible URL that is shown to your users (not page.php). You then use mod_rewrite in .htaccess to internally rewrite the visible URL back to the real/hidden filesystem path: /subdir1/subdir2/page1.php. (But I suspect you already know this, since your code is doing the right kind of thing.)
In your file hierarchy diagram, you appear to show subdir2 at the same level as subdir1? However, your code and URL structure suggests subdir2 is a subdirectory of subdir1. I'll assume the later.
You basically need to do two things:
Rewrite all requests to
/subdir1/subdir2/(except for requests that map directly to files or directories).Append the
.phpfile extension to requests that don't already have a file extension.
Try something like the following in the .htaccess file in the document root, ie. mysiteroot/.htaccess.
RewriteEngine On
# If the request has already been rewritten
# Or maps to an existing file then stop here.
# (Can't test for dir here since would not rewrite the doc root)
RewriteCond %{ENV:REDIRECT_STATUS} . [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# No file extension on request then append .php and rewrite to subdir
RewriteCond %{REQUEST_URI} /(.+)
RewriteRule !\.[a-z0-4]{2,4}$ /subdir1/subdir2/%1.php [NC,L]
# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /subdir1/subdir2/$1 [L]
Any request for /path/to/file (that does not directly map to a file) gets internally rewritten to /subdir1/subdir2/path/to/file.php.
The first RewriteCond directive ensures we don't rewrite requests that have already been rewritten to the subdirectory, thus preventing a rewrite loop.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
