使用htaccess缩短带变量的URL

时间:2015-10-17 16:00:41

标签: apache .htaccess mod-rewrite

是否可以使用htaccess文件,以便更改如下的URL:

http://example.com/index.php?a=profile&u=username123

进入这个?:

http://example.com/username123

如果是这样,我该怎么做呢?对不起,如果这个问题非常基础。

1 个答案:

答案 0 :(得分:1)

您可以将此代码放入htaccess(必须位于根文件夹中)

RewriteEngine On

# Redirect old format to new format (remove the 2 following lines if you don't want this)
RewriteCond %{THE_REQUEST} \s/index\.php\?a=profile&u=([^\s&]+)\s [NC]
RewriteRule ^ /%1? [R=301,L]

# Internally rewrite every non-existing file/folder in root folder to old format
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)$ /index.php?a=profile&u=$1 [L]

请勿忘记确保 mod_rewrite 已启用且允许htaccess(在apache配置中)