简体   繁体   中英

htaccess mod_rewrite: Simplifying URL

I've been having trouble with the following rewrite. I'm certain mod_rewrite is enabled but not sure where I am going wrong.

I'm try to change the following pattern:

/profile/?userid=157&username=FirstL

to:

/profile/FirstL

I've tried many different rules, but the two I felt were the closest to being correct aren't working at all. My current failures below:

RewriteEngine On
RewriteCond %{THE_REQUEST} \ /profile/+\?userid=$([^&\ ]+)&username=$([^&\ ]+)
RewriteRule ^ /%1? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ /profile/?userid=$1&username=$2 [L,QSA]

RewriteEngine On
RewriteRule ^([^/]*)$ /profile/?userid=$1&username=$2 [L]

Full htaccess:

    Options +FollowSymLinks -Multiviews

    RewriteEngine On
    RewriteCond %{THE_REQUEST} \ /profile/+\?userid=$([^&\ ]+)&username=$([^&\ ]+)
    RewriteRule ^ /profile/%1/%2? [L,R=301]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^profile/([^/]+)/([^/]+)$ /profile/?userid=$1&username=$2 [L,QSA]

    RewriteBase /

    DirectorySlash Off

    RewriteRule ^admin$ /admin/index.php [L,E=LOOP:1]

    RewriteCond %{ENV:REDIRECT_LOOP} !1
    RewriteRule ^admin/index.php$ /admin [R=301,L]

    # remove .php
    RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
    RewriteRule (.*)\.php$ $1 [R=301]

    # remove index
    RewriteRule (.*)/index$ $1/ [R=301]

    # remove slash if not directory
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} /$
    RewriteRule (.*)/ $1 [R=301]

    # add .php to access file, but don't redirect
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteCond %{REQUEST_URI} !/$
    RewriteRule (.*) $1\.php [L]

    #Force non-www:
    RewriteCond %{HTTP_HOST} www.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

You're losing the userID part of the URL, so when you try to internally rewrite that back, there's nothing there:

RewriteRule ^([^/]+)$ /profile/?userid=$1&username=$2 [L,QSA]

This rule says the first match is the "userid" and the second match is the "username", and you only have one match, and on top of that, it doesn't even begin with "profile".

You'll need to include the userid somewhere in the URL, otherwise there's no way to extract it.

RewriteEngine On
RewriteCond %{THE_REQUEST} \ /profile/+\?userid=([^&\ ]+)&username=([^&\ ]+)
RewriteRule ^ /profile/%1/%2? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^profile/([^/]+)/([^/]+)$ /profile/?userid=$1&username=$2 [L,QSA]

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