使用.htaccess mod_rewrite将部分URL重写到特定页面

时间:2018-08-28 15:01:30

标签: apache .htaccess mod-rewrite

真的不能为此找到一个标题,抱歉,这不是最好的。

我要重写这样的URL:

https://awesomechristianmusic.com/song-list?artist=dc-talk

看起来像这样:

https://awesomechristianmusic.com/dc-talk

或针对类型/主题:

https://awesomechristianmusic.com/song-list?genre=rock
https://awesomechristianmusic.com/song-list?topic=forgiveness

看起来像这样:

https://awesomechristianmusic.com/genre/rock
https://awesomechristianmusic.com/topic/forgiveness

不幸的是,我的.htaccess文件似乎存在一些问题,我无法弄清楚。这是我正在使用的东西:

RewriteEngine on
RewriteBase /

# Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,QSA,R=301]

# Remove www.
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ https://%1/$1 [R=301,L,QSA]

# Remove trailing slashes
RewriteCond %{REQUEST_URI} ^.*/$
RewriteRule ^(.*)/$ https://%{HTTP_HOST}/$1 [R=301,L,QSA]

# This is where I'm currently working
RewriteRule ^/([^/]+)$ /song-list?artist=$1 [NC,L,QSA]
RewriteRule ^/genre/([^/]+)$ /song-list?genre=$1 [NC,L,QSA]
RewriteRule ^/topic/([^/]+)$ /song-list?topic=$1 [NC,L,QSA]

# Redirect everything through index.php
RewriteCond %{REQUEST_URI} !(/(api|edit)/?.*) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [NC,L,QSA]

# long list of 301 redirects

当前,我正在处理的三个重写没有任何作用。如果我在正则表达式的开头删除斜杠,则会收到500 Internal Server Error。任何想法可能出什么问题或如何解决?

1 个答案:

答案 0 :(得分:0)

交换以下三个规则:

# This is where I'm currently working
RewriteRule ^/([^/]+)$ /song-list?artist=$1 [NC,L,QSA]
RewriteRule ^/genre/([^/]+)$ /song-list?genre=$1 [NC,L,QSA]
RewriteRule ^/topic/([^/]+)$ /song-list?topic=$1 [NC,L,QSA]

遵循这三个规则:

# If not /genre/* and not /topic/*
# Convert /dc-talk to /song-list?artist=dc-talk
RewriteCond %{REQUEST_URI} !^/genre/(.*)$ [NC]
RewriteCond %{REQUEST_URI} !^/topic/(.*)$ [NC]
RewriteRule ^(.*)$ song-list?artist=$1 [NC,L,QSA]

# Convert /genre/rock to /song-list?genre=rock
RewriteRule ^genre/(.*)$ song-list?genre=$1 [NC,L,QSA]

# Convert /topic/forgivenessto /song-list?topic=forgiveness
RewriteRule ^topic/(.*)$ song-list?topic=$1 [NC,L,QSA]

您可以在此处查看这些有效的规则:https://htaccess.madewithlove.be/?share=763f7107-f056-5ebe-ae0a-7f53a17b225a