简体   繁体   中英

Improving this url with .htaccess and mod_rewrite

I have a URL I want to shorten with a mod_rewrite.

In its ugliest form it looks like:

/img.php?i=15&a=92

Ideally it would look like:

/img/15/92

The problem is sometimes it might just be:

/img.php?i=15

In which case the person will enter:

/img/15

So I'm thinking I need a mod_rewrite like this:

RewriteRule ^/img/(.*)/(.*)$ /img.php?i=$1&a=$2

Which I imagine will work only when both variables are in the URL and not just the shortened version.

How do I make a single rewrite that works for both, or how do I make 2 without cancelling the other out?

Try this rule:

RewriteRule ^img/([0-9]+)(/([0-9]+))?$ img.php?i=$1&a=$3

When using mod_rewrite in a .htaccess file, you need to remove the per-directory path prefix from the pattern (in this case the leading / ). Because mod_rewrite does that too and puts back it after the rewrite process.

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