clean URL using .htaccess

▼魔方 西西 提交于 2019-12-01 07:44:17

问题


I'm trying to redirect the links on my domain. What I'm trying to achieve is: When the user clicks on a link to

mydomain.com/index.php?dir=myfolder

I want him to be redirected to exactly this URL but the browser bar is supposed to show this URL:

mydomain.com/myfolder

Since I don't have access to how the links are established (it's a php-site) I am trying to do this with just the .htaccess-file.

This is what I have:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} subdomain.mydomain.com
RewriteCond %{REQUEST_URI} (.*)/style.css [OR]
RewriteCond %{REQUEST_URI} (.*)/script.js [OR]
RewriteCond %{REQUEST_URI} (.*)/logo.png
RewriteRule (.*) http://www.subdomain.com%{REQUEST_URI} [R=301,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?dir=$1 [L]

So when I enter "mydomain.com/myfolder" into the browser it works fine and the URL in the address-bar stays like this. But when I enter "mydomain.com/index.php?dir=myfolder" it works as well but the URL also stays the same (which is not what I want). I assume that I need to somehow change the URL with the .htaccess-file and have it then (as I already have) rewritten to then php-scheme. I did several approaches now but I have no idea how to do this. I hope you understand my question and can help me!

Thank you!

EDIT:

The solution ( thanks to @anubhava):

RewriteEngine on
RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?dir=([^\s]+) [NC]
RewriteRule ^ %1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?dir=/$1 [L]

回答1:


Just append this rule at the end of your existing .htaccess file:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?dir=([^\s]+) [NC]
RewriteRule ^ %1? [R=301,L]



回答2:


I think you question is about making /index.php?dir=example redirect to /example. The below example issues a permanent redirection:

RewriteRule ^index\.php\?dir=?$ /$1 [NC,R=301,L]



回答3:


To prettify URLs of the format mydomain.com/index.php?dir=myfolder as mydomain.com/myfolder, try the following rewrite rule in your .htaccess file:

RewriteEngine on
RewriteRule ^([^/\.]+)/?$ /index.php?dir=$1 [L]


来源:https://stackoverflow.com/questions/12976342/clean-url-using-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!