如何反向编写干净的URL?

时间:2017-02-17 16:35:44

标签: apache .htaccess

我的htaccess中有以下内容

RewriteEngine On 

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^terms-and-conditions terms.php
RewriteRule ^privacy privacy.php
RewriteRule ^thank-you thanks.php

我怎样才能反向执行此操作,例如键入/privacy.php被重写为/ privacy。

1 个答案:

答案 0 :(得分:0)

您需要使用RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,NE,L] RewriteCond %{THE_REQUEST} \s/+terms\.php[\s?] [NC] RewriteRule ^ /terms-and-conditions [R=301,L] RewriteCond %{THE_REQUEST} \s/+privacy\.php[\s?] [NC] RewriteRule ^ /privacy [R=301,L] RewriteCond %{THE_REQUEST} \s/+thanks\.php[\s?] [NC] RewriteRule ^ /thank-you [R=301,L] RewriteRule ^terms-and-conditions/?$ terms.php [L,NC] RewriteRule ^privacy/?$ privacy.php [L,NC] RewriteRule ^thank-you/?$ thanks.php [L,NC] 变量使用3个单独的规则来避免重定向循环:

class Post(models.Model):
    poster = models.ForeignKey('auth.User')
    question = models.ForeignKey('self', null=True, blank=True)
    post_title = models.CharField(max_length=300)
    post_content = models.TextField(null=True, blank=True)

    is_published = models.BooleanField(default=True)
    is_locked = models.BooleanField(default=False)
    is_question = models.BooleanField(default=True)
    is_deleted = models.BooleanField(default=False)

    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)
    date_modified = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.post_title

class Vote(models.Model):
    user = models.ForeignKey('auth.User')
    post = models.ForeignKey('Post')
    vote_type = models.SmallIntegerField()#-1, 0, 1
    date_voted = models.DateTimeField(
            default=timezone.now)
    def __str__(self):
        return self.user