简体   繁体   中英

mod_rewrite query string with empty parameters

So I want to do a mod_rewrite in my .htaccess file so that the following browser request:

www.mysite.com/portal/v1/v2/v3

...will be rewritten and processed in php as this:

www.mysite.com/portal.php?n1=v1&n2=v2&n3=v3

The caveat here is that some or all of those GET variables could be blank, meaning the browser request could take any of the following forms:

www.mysite.com/portal/v1/v2/v3
www.mysite.com/portal/v1/v2
www.mysite.com/portal/v1
www.mysite.com/portal

I can sort things out in the php file, but what code should I use for .htaccess? Thanks!

Try this in your /.htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)/(.*)/(.*)/?$ /portal.php?n1=$1&n2=$2&n3=$3 [QSA,L,NC]

RewriteCond ensures that if the request is already for a file or directory RewriteRule will be skipped.

$1 $2 $3 refer to a pattern matched inside a RewriteRule .

You can use this code in your DOCUMENT_ROOT/.htaccess file:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ portal.php?n1=$1&n2=$2&n3=$3 [QSA,L]

RewriteRule ^([^/]+)/([^/]+)/?$ portal.php?n1=$1&n2=$2 [QSA,L]

RewriteRule ^([^/]+)/?$ portal.php?n1=$1 [QSA,L]

RewriteRule ^/?$ portal.php [L]

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