代码之家  ›  专栏  ›  技术社区  ›  lickmycode

mod_rewrite与组合2个条件/规则冲突

  •  0
  • lickmycode  · 技术社区  · 4 年前

    我正在使用此mod_rewrite规则 避免使用.php结尾 在我们的网站上:

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -f
    RewriteRule ^([^\.]+)$ $1.php [NC,L,QSA]
    

    效果很好,website.com/login.php变成website.com/log

    现在我想介绍一个用户名系统,使用 website.com/username

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/?$ /profile.php?user=$1 [L,QSA]
    

    两个规则/条件都按预期工作,但同时使用它们会导致冲突,例如自定义 “找不到配置文件” 消息,甚至在类似的页面上 术语.php

    有没有机会将这些规则/条件结合起来,首先检查是否有现有的.php文件,如果没有,请尝试配置文件用户名?甚至暗示如何更好地解决这个问题?

    示例: website.com/netsetter

    1. 如果存在netsetter.php,请使用netsetter.php
    2. 如果netsetter.php不存在,请使用profile.php?user=网络设置器

    更新(完整配置):

    <Directory "/var/www/vhosts/example.com/httpdocs">
    
    DirectoryIndex index.php
    
    # Apache configuration file
    # httpd.apache.org/docs/2.2/mod/quickreference.html
    
    # Note .htaccess files are an overhead, this logic should be in your Apache
    # config if possible: httpd.apache.org/docs/2.2/howto/htaccess.html
    
    # Techniques in here adapted from all over, including:
    #   Kroc Camen: camendesign.com/.htaccess
    #   perishablepress.com/press/2006/01/10/stupid-htaccess-tricks/
    #   Sample .htaccess file of CMS MODx: modxcms.com
    
    # ----------------------------------------------------------------------
    # Better website experience for IE users
    # ----------------------------------------------------------------------
    
    # Force the latest IE version, in various cases when it may fall back to IE7 mode
    #  github.com/rails/rails/commit/123eb25#commitcomment-118920
    # Use ChromeFrame if it's installed for a better experience for the poor IE folk
    
    <IfModule mod_headers.c>
        Header set X-UA-Compatible "IE=Edge,chrome=1"
        # mod_headers can't match by content-type, but we don't want to send this header on *everything*...
        <FilesMatch "\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|oex|xpi|safariextz|vcf)$" >
            Header unset X-UA-Compatible
        </FilesMatch>
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Cross-domain AJAX requests
    # ----------------------------------------------------------------------
    
    # Serve cross-domain Ajax requests, disabled by default.
    # enable-cors.org
    # code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
    
    #  <IfModule mod_headers.c>
    #    Header set Access-Control-Allow-Origin "*"
    #  </IfModule>
    
    # ----------------------------------------------------------------------
    # CORS-enabled images (@crossorigin)
    # ----------------------------------------------------------------------
    
    # Send CORS headers if browsers request them; enabled by default for images.
    # developer.mozilla.org/en/CORS_Enabled_Image
    # blog.chromium.org/2011/07/using-cross-domain-images-in-webgl-and.html
    # hacks.mozilla.org/2011/11/using-cors-to-load-webgl-textures-from-cross-domain-images/
    # wiki.mozilla.org/Security/Reviews/crossoriginAttribute
    
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            # mod_headers, y u no match by Content-Type?!
            <FilesMatch "\.(gif|png|jpe?g|svg|svgz|ico|webp)$">
                SetEnvIf Origin ":" IS_CORS
                Header set Access-Control-Allow-Origin "*" env=IS_CORS
            </FilesMatch>
        </IfModule>
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Webfont access
    # ----------------------------------------------------------------------
    
    # Allow access from all domains for webfonts.
    # Alternatively you could only whitelist your
    # subdomains like "subdomain.example.com".
    
    <IfModule mod_headers.c>
        <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$">
            Header set Access-Control-Allow-Origin "*"
        </FilesMatch>
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Proper MIME type for all files
    # ----------------------------------------------------------------------
    
    # JavaScript
    #   Normalize to standard type (it's sniffed in IE anyways)
    #   tools.ietf.org/html/rfc4329#section-7.2
    AddType application/javascript         js jsonp
    AddType application/json               json
    
    # Audio
    AddType audio/ogg                      oga ogg
    AddType audio/mp4                      m4a f4a f4b
    
    # Video
    AddType video/ogg                      ogv
    AddType video/mp4                      mp4 m4v f4v f4p
    AddType video/webm                     webm
    AddType video/x-flv                    flv
    
    # SVG
    #   Required for svg webfonts on iPad
    #   twitter.com/FontSquirrel/status/14855840545
    AddType     image/svg+xml              svg svgz
    AddEncoding gzip                       svgz
    
    # Webfonts
    AddType application/vnd.ms-fontobject  eot
    AddType application/x-font-ttf         ttf ttc
    AddType font/opentype                  otf
    AddType application/x-font-woff        woff
    
    # Assorted types
    AddType image/x-icon                        ico
    AddType image/webp                          webp
    AddType text/cache-manifest                 appcache manifest
    AddType text/x-component                    htc
    AddType application/xml                     rss atom xml rdf
    AddType application/x-chrome-extension      crx
    AddType application/x-opera-extension       oex
    AddType application/x-xpinstall             xpi
    AddType application/octet-stream            safariextz
    AddType application/x-web-app-manifest+json webapp
    AddType text/x-vcard                        vcf
    AddType application/x-shockwave-flash       swf
    AddType text/vtt                            vtt
    
    # ----------------------------------------------------------------------
    # Allow concatenation from within specific js and css files
    # ----------------------------------------------------------------------
    
    # e.g. Inside of script.combined.js you could have
    #   <!--#include file="libs/jquery-1.5.0.min.js" -->
    #   <!--#include file="plugins/jquery.idletimer.js" -->
    # and they would be included into this single file.
    
    # This is not in use in the boilerplate as it stands. You may
    # choose to use this technique if you do not have a build process.
    
    #<FilesMatch "\.combined\.js$">
    #  Options +Includes
    #  AddOutputFilterByType INCLUDES application/javascript application/json
    #  SetOutputFilter INCLUDES
    #</FilesMatch>
    
    #<FilesMatch "\.combined\.css$">
    #  Options +Includes
    #  AddOutputFilterByType INCLUDES text/css
    #  SetOutputFilter INCLUDES
    #</FilesMatch>
    
    # ----------------------------------------------------------------------
    # Gzip compression
    # ----------------------------------------------------------------------
    
    <IfModule mod_deflate.c>
    
        # Force deflate for mangled headers developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping/
        <IfModule mod_setenvif.c>
            <IfModule mod_headers.c>
                SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
                RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
            </IfModule>
        </IfModule>
    
        # Compress all output labeled with one of the following MIME-types
        <IfModule mod_filter.c>
            AddOutputFilterByType DEFLATE application/atom+xml \
            application/javascript \
            application/json \
            application/rss+xml \
            application/vnd.ms-fontobject \
            application/x-font-ttf \
            application/xhtml+xml \
            application/xml \
            font/opentype \
            image/svg+xml \
            image/x-icon \
            text/css \
            text/html \
            text/plain \
            text/x-component \
            text/xml
        </IfModule>
    
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Expires headers (for better cache control)
    # ----------------------------------------------------------------------
    
    # These are pretty far-future expires headers.
    # They assume you control versioning with filename-based cache busting
    # Additionally, consider that outdated proxies may miscache
    #   www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
    
    # If you don't use filenames to version, lower the CSS and JS to something like
    # "access plus 1 week".
    
    <IfModule mod_expires.c>
        ExpiresActive on
    
        # Perhaps better to whitelist expires rules? Perhaps.
        ExpiresDefault                          "access plus 1 month"
    
        # cache.appcache needs re-requests in FF 3.6 (thanks Remy ~Introducing HTML5)
        ExpiresByType text/cache-manifest       "access plus 0 seconds"
    
        # Your document html
        ExpiresByType text/html                 "access plus 0 seconds"
    
        # Data
        ExpiresByType text/xml                  "access plus 0 seconds"
        ExpiresByType application/xml           "access plus 0 seconds"
        ExpiresByType application/json          "access plus 0 seconds"
    
        # Feed
        ExpiresByType application/rss+xml       "access plus 1 hour"
        ExpiresByType application/atom+xml      "access plus 1 hour"
    
        # Favicon (cannot be renamed)
        ExpiresByType image/x-icon              "access plus 1 week"
    
        # Media: images, video, audio
        ExpiresByType image/gif                 "access plus 1 month"
        ExpiresByType image/png                 "access plus 1 month"
        ExpiresByType image/jpeg                "access plus 1 month"
        ExpiresByType video/ogg                 "access plus 1 month"
        ExpiresByType audio/ogg                 "access plus 1 month"
        ExpiresByType video/mp4                 "access plus 1 month"
        ExpiresByType video/webm                "access plus 1 month"
    
        # HTC files  (css3pie)
        ExpiresByType text/x-component          "access plus 1 month"
    
        # Webfonts
        ExpiresByType application/x-font-ttf    "access plus 1 month"
        ExpiresByType font/opentype             "access plus 1 month"
        ExpiresByType application/x-font-woff   "access plus 1 month"
        ExpiresByType image/svg+xml             "access plus 1 month"
        ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
    
        # CSS and JavaScript
        ExpiresByType text/css                  "access plus 1 year"
        ExpiresByType application/javascript    "access plus 1 year"
    
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Prevent mobile network providers from modifying your site
    # ----------------------------------------------------------------------
    
    # The following header prevents modification of your code over 3G on some
    # European providers.
    # This is the official 'bypass' suggested by O2 in the UK.
    
    # <IfModule mod_headers.c>
    # Header set Cache-Control "no-transform"
    # </IfModule>
    
    # ----------------------------------------------------------------------
    # ETag removal
    # ----------------------------------------------------------------------
    
    # FileETag None is not enough for every server.
    <IfModule mod_headers.c>
        Header unset ETag
    </IfModule>
    
    # Since we're sending far-future expires, we don't need ETags for
    # static content.
    #   developer.yahoo.com/performance/rules.html#etags
    FileETag None
    
    # ----------------------------------------------------------------------
    # Stop screen flicker in IE on CSS rollovers
    # ----------------------------------------------------------------------
    
    # The following directives stop screen flicker in IE on CSS rollovers - in
    # combination with the "ExpiresByType" rules for images (see above).
    
    # BrowserMatch "MSIE" brokenvary=1
    # BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
    # BrowserMatch "Opera" !brokenvary
    # SetEnvIf brokenvary 1 force-no-vary
    
    # ----------------------------------------------------------------------
    # Set Keep-Alive Header
    # ----------------------------------------------------------------------
    
    # Keep-Alive allows the server to send multiple requests through one
    # TCP-connection. Be aware of possible disadvantages of this setting. Turn on
    # if you serve a lot of static content.
    
    # <IfModule mod_headers.c>
    #   Header set Connection Keep-Alive
    # </IfModule>
    
    # ----------------------------------------------------------------------
    # Cookie setting from iframes
    # ----------------------------------------------------------------------
    
    # Allow cookies to be set from iframes (for IE only)
    # If needed, specify a path or regex in the Location directive.
    
    # <IfModule mod_headers.c>
    #   Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""
    # </IfModule>
    
    # ----------------------------------------------------------------------
    # Start rewrite engine
    # ----------------------------------------------------------------------
    
    # Turning on the rewrite engine is necessary for the following rules and
    # features. FollowSymLinks must be enabled for this to work.
    
    # Some cloud hosting services require RewriteBase to be set
    # If using the h5bp in a subdirectory, use `RewriteBase /foo` instead where
    # 'foo' is your directory.
    
    # If your web host doesn't allow the FollowSymlinks option, you may need to
    # comment it out and use `Options +SymLinksOfOwnerMatch`, but be aware of the
    # performance impact
    
    <IfModule mod_rewrite.c>
        Options +FollowSymlinks
        # Options +SymLinksIfOwnerMatch
        RewriteEngine On
        # RewriteBase /
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Suppress or force the "www." at the beginning of URLs
    # ----------------------------------------------------------------------
    
    # The same content should never be available under two different URLs -
    # especially not with and without "www." at the beginning, since this can cause
    # SEO problems (duplicate content). That's why you should choose one of the
    # alternatives and redirect the other one.
    
    # By default option 1 (no "www.") is activated.
    # no-www.org/faq.php?q=class_b
    
    # If you'd prefer to use option 2, just comment out all option 1 lines
    # and uncomment option 2.
    
    # IMPORTANT: NEVER USE BOTH RULES AT THE SAME TIME!
    
    # ----------------------------------------------------------------------
    
    # Option 1:
    # Rewrite "www.example.com -> example.com".
    
    <IfModule mod_rewrite.c>
        RewriteCond %{HTTP_HOST} !^example.com$
        RewriteRule ^(.*)$ https://example.com/$1 [R,L]
        RewriteCond %{HTTPS} !=on
        RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
        RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
        RewriteCond %{HTTP_HOST} ([^.]+)\.example.com [NC]
        RewriteRule ^(.*) https://example.com/
    </IfModule>
    
    # ----------------------------------------------------------------------
    
    # Option 2:
    # Rewrite "example.com -> www.example.com".
    # Be aware that the following rule might not be a good idea if you use "real"
    # subdomains for certain parts of your website.
    
    # <IfModule mod_rewrite.c>
    #   RewriteCond %{HTTPS} !=on
    #   RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
    #   RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    # </IfModule>
    
    # ----------------------------------------------------------------------
    # Built-in filename-based cache busting
    # ----------------------------------------------------------------------
    
    # If you're not using the build script to manage your filename version revving,
    # you might want to consider enabling this, which will route requests for
    # /css/style.20110203.css to /css/style.css
    
    # To understand why this is important and a better idea than all.css?v1231,
    # read: github.com/h5bp/html5-boilerplate/wiki/cachebusting
    
    # <IfModule mod_rewrite.c>
    #   RewriteCond %{REQUEST_FILENAME} !-f
    #   RewriteCond %{REQUEST_FILENAME} !-d
    #   RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
    # </IfModule>
    
    # ----------------------------------------------------------------------
    # Prevent SSL cert warnings
    # ----------------------------------------------------------------------
    
    # Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent
    # https://www.example.com when your cert only allows https://secure.example.com
    
    <IfModule mod_rewrite.c>
        RewriteCond %{SERVER_PORT} !^443
        RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
        RewriteCond %{HTTPS} !=on
        RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    </IfModule>
    
    # ----------------------------------------------------------------------
    # Prevent 404 errors for non-existing redirected folders
    # ----------------------------------------------------------------------
    
    # without -MultiViews, Apache will give a 404 for a rewrite if a folder of the
    # same name does not exist.
    # webmasterworld.com/apache/3808792.htm
    
    Options -MultiViews
    
    # ----------------------------------------------------------------------
    # Custom 404 page
    # ----------------------------------------------------------------------
    
    # You can add custom pages to handle 500 or 403 pretty easily, if you like.
    # If you are hosting your site in subdirectory, adjust this accordingly
    #    e.g. ErrorDocument 404 /subdir/404.html
    ErrorDocument 404 /index.php
    
    # ----------------------------------------------------------------------
    # UTF-8 encoding
    # ----------------------------------------------------------------------
    
    # Use UTF-8 encoding for anything served text/plain or text/html
    AddDefaultCharset utf-8
    
    # Force UTF-8 for a number of file formats
    AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
    
    # ----------------------------------------------------------------------
    # A little more security
    # ----------------------------------------------------------------------
    
    # "-Indexes" will have Apache block users from browsing folders without a
    # default document Usually you should leave this activated, because you
    # shouldn't allow everybody to surf through every folder on your server (which
    # includes rather private places like CMS system folders).
    <IfModule mod_autoindex.c>
        Options -Indexes
    </IfModule>
    
    # Block access to "hidden" directories or files whose names begin with a
    # period. This includes directories used by version control systems such as
    # Subversion or Git.
    <IfModule mod_rewrite.c>
        RewriteCond %{SCRIPT_FILENAME} -d [OR]
        RewriteCond %{SCRIPT_FILENAME} -f
        RewriteRule "(^|/)\." - [F]
    </IfModule>
    
    # Block access to backup and source files. These files may be left by some
    # text/html editors and pose a great security danger, when anyone can access
    # them.
    <FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
        Order allow,deny
        Deny from all
        Satisfy All
    </FilesMatch>
    
    # If your server is not already configured as such, the following directive
    # should be uncommented in order to set PHP's register_globals option to OFF.
    # This closes a major security hole that is abused by most XSS (cross-site
    # scripting) attacks. For more information: http://php.net/register_globals
    #
    # IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS:
    #
    # Your server does not allow PHP directives to be set via .htaccess. In that
    # case you must make this change in your php.ini file instead. If you are
    # using a commercial web host, contact the administrators for assistance in
    # doing this. Not all servers allow local php.ini files, and they should
    # include all PHP configurations (not just this one), or you will effectively
    # reset everything to PHP defaults. Consult www.php.net for more detailed
    # information about setting PHP directives.
    
    # php_flag register_globals Off
    
    # Rename session cookie to something else, than PHPSESSID
    # php_value session.name sid
    
    # Disable magic quotes (This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.)
    # php_flag magic_quotes_gpc Off
    
    # Do not show you are using PHP
    # Note: Move this line to php.ini since it won't work in .htaccess
    # php_flag expose_php Off
    
    # Level of log detail - log all errors
    # php_value error_reporting -1
    
    # Write errors to log file
    # php_flag log_errors On
    
    # Do not display errors in browser (production - Off, development - On)
    # php_flag display_errors Off
    
    # Do not display startup errors (production - Off, development - On)
    # php_flag display_startup_errors Off
    
    # Format errors in plain text
    # Note: Leave this setting 'On' for xdebug's var_dump() output
    # php_flag html_errors Off
    
    # Show multiple occurrence of error
    # php_flag ignore_repeated_errors Off
    
    # Show same errors from different sources
    # php_flag ignore_repeated_source Off
    
    # Size limit for error messages
    # php_value log_errors_max_len 1024
    
    # Don't precede error with string (doesn't accept empty string, use whitespace if you need)
    # php_value error_prepend_string " "
    
    # Don't prepend to error (doesn't accept empty string, use whitespace if you need)
    # php_value error_append_string " "
    
    # Increase cookie security
    <IfModule php5_module>
        php_value session.cookie_httponly true
    </IfModule>
    
    # Avoid directory browsing
    Options All -Indexes
    
    # Protecting *.tpl files
    <Files "*.tpl">
        Order allow,deny
        Deny from all
    </Files>
    # compress text, HTML, JavaScript, CSS, and XML
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    
    # remove browser bugs
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    Header append Vary User-Agent
    
    RewriteEngine On
    Options +Followsymlinks
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.* - [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^.*/images/(.*)$ /images/$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^.*/uploads_user/(.*)$ /uploads_user/$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/?$ /profile.php?user_id=$1 [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^@([0-9]+)/?$ /profile.php?user_id=$1 [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^@([^/]+)/?$ /profile.php?user=$1 [L,QSA]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^id([0-9]+)/?$ /profile.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/([^/]+)?$ /profile.php?user=$1$2 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/albums/([0-9]+)/([0-9]+)/?$ /album_file.php?user_id=$1&album_id=$2&media_id=$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/albums/([0-9]+)/([0-9]+)/?$ /album_file.php?user=$1&album_id=$2&media_id=$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/albums/([0-9]+)/?$ /album.php?user_id=$1&album_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/albums/([0-9]+)/?$ /album.php?user=$1&album_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/albums/([0-9]+)/([^/]+)?$ /album.php?user_id=$1&album_id=$2$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/albums/([0-9]+)/([^/]+)?$ /album.php?user=$1&album_id=$2$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/albums/?$ /albums.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/albums/?$ /albums.php?user=$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/netmails/?$ /netmails.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/netmails/?$ /netmails.php?user=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/netmails/([0-9]+)/?$ /netmails.php?user_id=$1&netmail_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/netmails/([0-9]+)/?$ /netmails.php?user=$1&netmail_id=$2 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/blog/([0-9]+)/?$ /blog.php?user_id=$1&blogentry_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/blog/([0-9]+)/?$ /blog.php?user=$1&blogentry_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/blog/([^/]+)?$ /blog.php?user_id=$1$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/blog/([^/]+)?$ /blog.php?user=$1$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/blog/?$ /blog.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/blog/?$ /blog.php?user=$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/trackback/([0-9]+)/?$ /blog_ajax.php?task=trackback&user=$1&blogentry_id=$2 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*/)?group/([0-9]+)/([^/]*)$ /group.php?group_id=$1$2$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*/)?group/([0-9]+)/album/([0-9]+)/([^/]*)$ /group_album.php?group_id=$2&groupalbum_id=$3$4 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*/)?group/([0-9]+)/album/([0-9]+)/([0-9]+)/([^/]*)$ /group_album_file.php?group_id=$2&groupalbum_id=$3&groupmedia_id=$4$5 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*/)?group/([0-9]+)/discussion/([0-9]+)/([^/]*)$ /group_discussion_view.php?group_id=$2&grouptopic_id=$3$4 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*/)?group/([0-9]+)/discussion/([0-9]+)/([0-9]+)/([^/]*)$ /group_discussion_view.php?group_id=$2&grouptopic_id=$3&grouppost_id=$4$5 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*/)?group/([0-9]+)/poll/([0-9]+)/([^/]*)$ /group_poll.php?group_id=$2&poll_id=$3$4 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/audio/?$ /audio.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/audio/?$ /audio.php?user=$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/videos/?$ /videos.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/videos/?$ /videos.php?user=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/videos/([0-9]+)/?$ /video.php?user_id=$1&video_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/videos/([0-9]+)/?$ /video.php?user=$1&video_id=$2 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/polls/([0-9]+)/?$ /poll.php?user_id=$1&poll_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/polls/([0-9]+)/?$ /poll.php?user=$1&poll_id=$2 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/polls/([0-9]+)/([^/]+)?$ /poll.php?user_id=$1&poll_id=$2$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/polls/([0-9]+)/([^/]+)?$ /poll.php?user=$1&poll_id=$2$3 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([0-9]+)/polls/?$ /polls.php?user_id=$1 [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/polls/?$ /polls.php?user=$1 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^de https\:\/\/example\.com\/?lang_id=10 [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # Add additional file extensions to the list as needed.
    RewriteCond %{REQUEST_FILENAME} \.(jpg)$
    RewriteRule (.*) /images/nophoto.jpg
    
    # Avoid .php Endings
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -f
    RewriteRule ^([^\.]+)$ $1.php [NC,L,QSA]
    
    
    
    RewriteCond %{HTTP_HOST} !^example\.com [NC]
    RewriteCond %{HTTP_HOST}   !^$
    RewriteRule ^/?(.*)         https://example.com/$1 [L,R,NE]
    
    RewriteCond %{HTTP_HOST} ^example.de [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.example\.net$ [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.example\.de$ [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.example\.org$ [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.example\.info$ [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.example\.at$ [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.example\.ch$
    RewriteRule (.*) https://example.com/$1 [R=301,L]
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   MrWhite    4 年前

    假设这些指令直接在服务器配置(或虚拟主机)中,而不是 <Directory> 容器或 .htaccess 文件

    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -f
    RewriteRule ^([^\.]+)$ $1.php [NC,L,QSA]
    

    旁白: 第二个 条件 这里没有意义。它在附加之前检查初始请求是否映射到文件 .php 。你当然不想附加 .php 如果初始请求确实映射到文件。幸运的是,它完全是多余的,因为 RewriteRule 图案 ^([^\.]+)$ 排除了点,所以该规则自然地排除了无论如何都会映射到实际文件的请求(除非您的文件没有文件扩展名——非常不可能)。

    只有第一个 条件 它检查请求是否没有映射到此处实际使用的目录。

    然后,无论目标是否 .php 文件是否存在。最好先检查一下,这将有助于解决您与用户名的冲突(正如您所建议的)。

    NB:你真的应该使用 REQUEST_URI 此处的变量(或 $1 backreference)而不是 REQUEST_FILENAME 请求文件名 旨在包含绝对文件系统路径,因此将其附加到 DOCUMENT_ROOT 通常没有意义。只是当用于 服务器 (或 虚拟主机 )上下文, 请求文件名 包含与相同的 请求URI (即根相对URL路径)。

    效果很好,website.com/login.php变成website.com/log

    旁白: 这个规则实际上起到了完全相反的作用。 /login 变成 /login.php 。另一种方法是外部重定向和不同的指令。

    因此,将以上内容更改为:

    RewriteCond %{DOCUMENT_ROOT}$1.php -f
    RewriteRule ^([^.]+)$ $1.php [L]
    

    这将检查请求+ .php 在重写请求之前已存在。在检查请求之前,无需检查请求是否直接映射到+ .php 确实映射到文件。

    不需要对正则表达式字符类中的文字点进行反斜杠转义。

    不需要 NC QSA 旗帜。正则表达式已经不区分大小写,因为它同时匹配a-z和a-z。除非在 替代

    然后,如果用户名不能包含点,则可以使用以下规则来管理 /username 。例如:

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/.]+)/?$ /profile.php?user=$1 [L,QSA]
    

    您可能需要先检查请求是否映射到目录的条件。

    然而, 用户名 可以包含,然后从正则表达式中删除点,并包含一个附加条件以排除已映射到文件(在文档根目录中)的请求:

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/?$ /profile.php?user=$1 [L,QSA]
    

    总结

    # Extensionless URLs
    RewriteCond %{DOCUMENT_ROOT}$1.php -f
    RewriteRule ^([^.]+)$ $1.php [L]
    
    # Rewrite "/Usernames"
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^/]+)/?$ /profile.php?user=$1 [L,QSA]
    
    推荐文章