PHP - 使用.htaccess重写规则隐藏URL中的文件夹名称
I'm doing a small php personal project for fun and I need help with my rewrite rules. My goal is to hide completely a folder name in my URL.
Here's what I got already :
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/my-app/
RewriteRule ^(.*)$ /my-app/$1 [L]
</IfModule>
This is working fine, I don't need to specify my-app folder in the URL but when I redirect to another page the folder name is displayed again. What can I do to specify that when my-app folder is requested, to hide it from the URL. Thanks in advance.
我正在做一个小型的PHP个人项目以获得乐趣,我需要帮助我的重写规则。 我的目标是在我的URL中完全隐藏文件夹名称。 p>
这是我已经得到的: p>
&lt; IfModule mod_rewrite.c&gt ;
RewriteEngine on
RewriteCond%{REQUEST_URI}!^ / my-app /
RewriteRule ^(。*)$ / my-app / $ 1 [L]
&lt; / IfModule&gt;
code>
这很好用,我不需要在URL中指定my-app文件夹,但是当我重定向到另一个页面时,文件夹名称会再次显示。 我该怎么做才能指定在请求my-app文件夹时将其隐藏在URL中。 提前致谢。 p>
div>
Try adding this rule to your htaccess file:
RewriteCond %{THE_REQUEST} \ /+my-app/
RewriteRule ^my-app/(.*)$ /$1 [L,R=301]
This will redirect any direct request for anything in /my-app/
to a URL with it removed.
This is a tested and working example that I have in my local app
RewriteEngine on
RewriteBase /
# Add trailing slash
RewriteCond %{REQUEST_URI} !(\.|/$)
RewriteRule (.*) http://%{HTTP_HOST}/$1/ [R=302,L]
RewriteCond %{QUERY_STRING} !^qs
RewriteRule ^my-app(.*)$ $1 [R=302,L]
RewriteCond %{REQUEST_URI} !^/my-app/
RewriteRule ^(.*)/$ my-app/?qs=$1 [L,QSA]
This is how I redirect to
domain.com/subcat
When the url is
domain.com/my-app/subcat
I have the query string qs
to avoid redirects like:
domain.com/?qs=subcat
To get the url just use $_GET var
var_dump($_GET);
Output
array (size=1)
'qs' => string 'subcat' (length=3)
Replace R=302
with R=301
if it works for you
EDIT:
A better solution, without the query string qs
# Avoid redirect loop
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule ^ - [L]
# Add trailing slash
RewriteCond %{REQUEST_URI} !(\.|/$)
RewriteRule (.*) http://%{HTTP_HOST}/$1/ [R=302,L]
RewriteRule ^my-app(.*)$ $1 [R=302,L]
RewriteCond %{REQUEST_URI} !^/my-app/
RewriteRule ^(.*)/$ my-app/$1 [L,QSA]