2015-11-06 332 views
2

我有一篇博客用php編寫了幾篇文章,但要閱讀一篇帖子,url應該是http://myblog/post.php?url=an-article-tilte&id=7用NGINX重寫URL

我想做出一個最明智的方式來訪問與他們的網址的文章(並改善參考)。在我的數據庫中,每篇文章都有一個url屬性,其中包含'kebab-case'中的標題(例如,'歡迎來到我的博客'將是'welcome-to-my-blog')。總而言之,要訪問'Welcome to my blog'帖子(id等於7),我會輸入http://myblog.com/post/welcome-to-my-blog-7而不是http://myblog.com/post.php?url=welcome-to-my-blog&id=7

在我的博客上nginx的配置文件,我有這樣的:

server { 
    listen 80; 
    root /opt/http/nginx/sites/myblog/www; 
    index index.php index.html; 
    server_name myblog.com www.myblog.com; 

    location/{ 
     try_files $uri $uri/ /index.php; 
    } 

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { 
     expires 365d; 
    } 

    location ~* \.(pdf)$ { 
     expires 30d; 
    } 

    client_max_body_size 3M; 

    error_page 403 /index.php; 

    # pass the PHP scripts to FastCGI server listening on /var/run/php5-fpm.sock 
    location ~ \.php$ { 
     try_files $uri =404; 
     fastcgi_pass unix:/var/run/php5-fpm.sock; 
     fastcgi_index index.php; 
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
     include fastcgi_params; 
    } 

    gzip on; 
    gzip_min_length 1100; 
    gzip_buffers 4 32k; 
    gzip_types text/plain application/x-javascript text/xml text/css; 
    gzip_vary on; 

    access_log /var/log/nginx/www.myblog.access.log; 
    error_log /var/log/nginx/www.myblog.error.log; 
} 

而且我想我必須把裏面這樣的事情,但它是一個錯誤,當我嘗試重新啓動nginx的。所以我不知道它有什麼問題。

location @rewrites { 
    if ($uri ~* ^/post/([a-zA-Z0-0\-]+)-([0-9]+)) { 
     rewrite ^/post.php?url=$1&id=$2; 
    } 
} 

用apache很容易,但有沒有辦法在nginx上重現它?

回答

1

我認爲這個問題是缺少美元$關閉正則表達式字符串,可以無論如何重寫規則如下:

location /post/ { 
    rewrite ^/post/([\w-]+)-(\d+)$ /post.php?url=$1&id=$2; 
} 

其中:

  • \w相當於[a-zA-Z0-9_](如果你更喜歡刪除unescore _在擴展版本中重寫它)
  • \d[0-9]

:如果您使用~*這是一個不區分大小寫的匹配(不需要雙A-Za-z)。

UPDATE:如果我正確理解你需要什麼,我們不得不重新改寫規則做相反的(主動要求post.php?url={kebab-title}&id={id-number}和實際取得的`網址`後/ {烤肉標題} - { ID號碼}

location ~ ^/post\.php\?url=(.*)&id=(\d*)$ { 
    alias /post/$1-$2; 
} 

更新2 避免/post/下不需要的匹配,你也可以使用這種替代(更具體的)版本:

location ~ ^/post/((?:\w+-)+\w+)-(\d+)$ { 
    rewrite /post.php?url=$1&id=$2; 
} 
+0

我提高了你的答案,因爲這正是我一直在尋找的想法!而現在,我在鏈接'http:// myblog.com/post/an-example-article-8'上有了404。但我相信我們會解決這個問題! –

+1

@MaximeLafarie:嘗試更新中提出的解決方案,我認爲是你需要的。 –

+0

我很抱歉,您的第一個答案像魅力一樣工作!我忘記的是,我的博客位於「博客」目錄中,然後我必須在代碼中的所有'/'之前添加'/ blog'以適應您的答案。我在任何地方都做到了,但我忘了在這裏做:'/post.php?url=$1 &id=$2;'。感謝您的回答,這正是我所尋找的,並感謝您,我現在瞭解了nginx url重寫的工作原理。 –