Hide Page Extensions (Like StackOverflow)

前端 未结 6 1226
故里飘歌
故里飘歌 2020-12-07 04:42

I want to hide page extensions like stackoverflow does. How does the following work?

http://stackoverflow.com/tags/foo
http://stackoverflow.com/tags/bar
         


        
6条回答
  •  囚心锁ツ
    2020-12-07 05:02

    If you're using Apache and you simply want to hide the file extensions of static HTML files you can use this .htaccess code:

    
    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f       # if the requested URL is not a file that exists
    RewriteCond %{REQUEST_FILENAME} !-d       # and it isn't a directory that exists either
    RewriteCond %{REQUEST_FILENAME}\.html -f  # but when you put ".html" on the end it is a file that exists
    RewriteRule ^(.+)$ $1\.html [QSA]         # then serve that file
    
    
    

    Apache mod_rewrite has been called "voodoo, but seriously cool voodoo".

    The actual .htaccess code I use on a few sites is like that, but not identical:

    
        RewriteEngine on
    
        #RewriteRule ^$ index.php [QSA]
        RewriteCond %{REQUEST_FILENAME}\.php -f
        RewriteRule ^(.+)$ $1\.php [QSA]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.+)$ index.php/$1 [QSA]
    
    
    

    And here is some much longer but far more readable code to do the same thing on a Zeus server. On Zeus, it's called rewrite.script.

    # http://drupal.org/node/46508
    
    
    # get the document root
    map path into SCRATCH:DOCROOT from /
    # initialize our variables
    set SCRATCH:ORIG_URL = %{URL}
    set SCRATCH:REQUEST_URI = %{URL}
    
    match URL into $ with ^(.*)\?(.*)$
    if matched then
      set SCRATCH:REQUEST_URI = $1
      set SCRATCH:QUERY_STRING = $2
    endif
    
    # prepare to search for file, rewrite if its not found
    set SCRATCH:REQUEST_FILENAME = %{SCRATCH:DOCROOT}
    set SCRATCH:REQUEST_FILENAME . %{SCRATCH:REQUEST_URI}
    
    # check to see if the file requested is an actual file or
    # a directory with possibly an index.  don't rewrite if so
    look for file at %{SCRATCH:REQUEST_FILENAME}
    if not exists then
      look for dir at %{SCRATCH:REQUEST_FILENAME}
      if not exists then
        look for file at  %{SCRATCH:REQUEST_FILENAME}.php
        if exists then
            set URL = %{SCRATCH:REQUEST_URI}.php?%{SCRATCH:QUERY_STRING}
        else
            set URL = /index.php/%{SCRATCH:REQUEST_URI}?%{SCRATCH:QUERY_STRING}
        endif
      endif
    endif
    goto END
    

提交回复
热议问题