简体   繁体   中英

PHP .htaccess removing .php extension and language directory to parameter

I'm looking for a regulair expression for a .htaccess file inside my PHP server.

What I want is that it detects the language from the first directory as parameter:

  • nl
  • en
  • be
  • de

Any other options must be treated as a directory or filename. The language must be given as parameter without corrupting any other parameters.

Also I want the last / replaced by .php .

Some examples:

host.com/nl/index/ -> host.com/index.php?lang=nl
host.com/de/test/abc/ -> host.com/test/abc.php?lang=de
host.com/be/a/b/c/?t=23 -> host.com/a/b/c.php?lang=be&t=23

Is this possible? I can't get it to work, I hope someone will help me out!

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule >>> requested expression and replacing pattern <<<
</IfModule>
RewriteRule ^/([a-z]{2})(/.+)/?$ $2.php?lang=$1 [QSA]

Regexes are easiest to interpret by considering a piece at a time. Let's break that down:

  • ^ - start of URL
  • / - match first slash
  • ([az]{2}) - match and capture 2 letters (goes into the $1 variable)
  • ( - begin capture group (goes into $2 )
  • / - match a slash
  • .+ - match zero or more characters
  • ) - end capture group ( $2 )
  • /? - match an OPTIONAL end slash of the "file path" (but don't capture it)
  • $ - end of URL

So, you're capturing two things:

1 . the language (capture group $1 ):

([a-z]{2})

2 . the file path , starting with a slash (capture group $2 ), followed by an optional slash:

(/.+)/?

Finally, the QSA flag at the end appends your original query string (if there was one) to your rewritten URL. If you'd like to make your regex match case-insensitive (ie allow URLs like host.com/NL/index/ ), you can add the NC flag too: [QSA,NC] . Alternatively, you could explicitly allow capital letters by using [A-Za-z] instead of [az] in your regex.

尝试这个

RewriteRule ^([a-z]{2})/(.+)/?$ /$2.php?lang=$1 [QSA]

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$2.php -f
RewriteRule ^([a-z]{2})/(.+?)/?$ /$2.php?lang=$1 [L,QSA,NC]

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