.htaccess basic url rewrites

心已入冬 提交于 2019-12-12 01:07:54

问题


There are a few things I want done to the URLs of my site that I cannot seem the .htaccess file to do.

1 remove file extension f.e. example.com/file.php should be example.com/file

2 remove the www. f.e. www.example.com should be example.com (I got this part to work, but I would hate it if after I put in fix and this no longer worked

3 no one should be able to see index.php at the end of root f.e. example.com/index.php should be example.com

4 my blog page should have nice urls f.e. example.com/blog.php?article=the-name-of-article should be example.com/blog/the-name-of-article

here is my current .htaccess file

rewrite URLs

Options +FollowSymLinks -MultiViews
rewriteengine on
RewriteBase /

## Hide .php extension
## To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php

## remove www
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]

## remove ugly part of url for blog.php
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
RewriteRule ^blog/(.*)$ blog.php?article=$1 [QSA,L]

when I try to go to blog/the-name-of-article I get a internal server error.


回答1:


From the body and comments of your .htaccess it appears that I would have provided it in the past :P

Only thing wrong in your .htaccess is ordering of rules. Always have them from most specific to most generic. Have your code like this:

Options +FollowSymLinks -MultiViews
rewriteengine on
RewriteBase /

## remove www
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
## remove ugly part of url for blog.php
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

RewriteRule ^blog/(.*)$ /blog.php?article=$1 [QSA,L]

## Hide .php extension
## To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,NC]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php



回答2:


To remove .php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

see Remove .php extensions with .htaccess without breaking DirectoryIndex

EDIT For pretty URLs check this tutorial: http://net.tutsplus.com/tutorials/other/using-htaccess-files-for-pretty-urls/



来源:https://stackoverflow.com/questions/16865958/htaccess-basic-url-rewrites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!